PHP class: assigning a static property via constructor

A simplified class example:

class Table extends TableAbstract{ protected static $tablename; function __construct($str){ $this->tablename = "table_" . $str; $this->insert(); // abstract function } } 

When I used these classes before, I assigned $ tablename directly when writing the class. This time I would like the constructor to define this. But when I call a function that references $ tablename, the variable seems empty when I echo SQL.

What am I doing wrong, or can someone suggest a way to achieve what I want here?

Thanks for any comments / answers.

+6
source share
5 answers

As a static property, refer to it using Table::$tablename - or, alternatively, self::$tablename to implicitly refer to the current class.

+6
source

when accessing a static property you need to use self::$varName instead of $this->varName . Same thing with static methods.

Edit: To highlight some of the differences between abstract and static / non-static properties, I made a small example.

 <?php abstract class A{ public abstract function setValue($someValue); public function test(){ echo '<pre>'; var_dump($this->childProperty); var_dump(B::$childStatic); echo '</pre>'; } } class B extends A{ protected $childProperty = 'property'; protected static $childStatic = 'static'; public function setValue($someValue){ $this->childProperty = $someValue; self::$childStatic = $someValue; } } //new instance of B $X = new B(); //another new instance of B $Y = new B(); //output the values $X->test(); $Y->test(); //change the static and standard property in $X $X->setValue("some new value"); //output the values again. $X->test(); $Y->test(); ?> 

Conclusion:

 string(8) "property" string(6) "static" string(8) "property" string(6) "static" string(14) "some new value" string(14) "some new value" string(8) "property" string(14) "some new value" 

After calling setValue in $ X, you will see that the values โ€‹โ€‹of the static property change in both instances, while the non-static properties change in only one instance.

Also, I just found out something. In the method of an abstract class trying to access a static child property, you must specify the name of the child class to access the property, self:: does not work and throws an error.

+2
source

If you would set yourself such a thing as php static, you would find that:

From PHP Manual :

Static keyword

Static properties are not accessible through the object using the arrow operator โ†’.

+2
source

static properties are set in the class, not in the instance. Get rid of static to make your $tablename property a normal instance, and it should work as expected.

+1
source

the static member is not bound to the instance, but it is more associated with the class, so you cannot refer to the static member via $this . you must use self::$staticMemberName to access the static element from the class instance.

+1
source

Source: https://habr.com/ru/post/891321/


All Articles