Simplified example of a class:
class Table extends TableAbstract{
protected static $tablename;
function __construct($str){
$this->tablename = "table_" . $str;
$this->inser开发者_如何学JAVAt(); // 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..
As the property is static
, access it using Table::$tablename
- or alternatively self::$tablename
to refer implicitly to the current class.
If you would google up such thing as php static you would have found that:
From PHP Manual:
Static Keyword
Static properties cannot be accessed through the object using the arrow operator ->.
when accessing a static property you need to use self::$varName
instead of $this->varName
. Same thing with static methods.
Edit: Just to highlight some 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();
?>
Output:
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 you call setValue on $X, it you can see that the values of the static property change in both the instances while the non-static property changes only in that one instance.
Also, I just learned something. In a method of an abstract class trying to access a static child property, you have to specify the child class name to access the property, self::
doesn't work and throws an error.
static
properties are set on the class, not on an instance. Get rid of the static
to make your $tablename
a normal instance property and it should work as expected.
a static member is not tied up to the instance but it's more related to the class, so you can't really reference a static member through $this
. you should use self::$staticMemberName
to access a static member from within a class instance.
精彩评论