Simplified example of a class:
class Table extends TableAbstract{
protected static $tablename;
function __construct($str){
$this->tablename = "table_" . $str;
$this->insert(); // abstract function
}
}
When I've used classes like this in the past I've assigned the $tablename directly when writing the class. This time however I would like it to be decided by the constructor. But when I then call the function referencing $tablename the variable seems to be empty, when I echo the SQL.
What am I doing wrong, or could someone suggest a way to achieve what I want here?
Thanks for any comments/answers..
A static constructor is just a method the developer can define on a class which can be used to initialise any static properties, or to perform any actions that only need to be performed only once for the given class. The method is only called once as the class is needed.
The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.
A static method has two main purposes: For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.
The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.
As the property is static
, access it using Table::$tablename
- or alternatively self::$tablename
to refer implicitly to the current class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With