PHP cannot override protected static
I can't seem to be able to override protected static
variables. It's rather annoying, given that you cannot override any private variable as well. Howcan I fix that? (Have to support PHP 5.2)
<?
class Foo{
pro开发者_Go百科tected static $stuff = 'Foo';
public function showStuff(){
echo self::$stuff . PHP_EOL;
}
}
class Bar extends Foo{
protected static $stuff = 'Bar';
}
$f = new Foo();
$b = new Bar();
$f->showStuff(); // Output: Foo
$b->showStuff(); // Output: Foo
?>
You need to use late static bindings, a feature introduced in PHP 5.3. In your class Foo
, self
refers to the Foo
class. You want to refer to the class where the call originated. You need to use the keyword static
:
<?
class Foo{
protected static $stuff = 'Foo';
public function showStuff(){
echo static::$stuff . PHP_EOL; // <-- this line
}
}
class Bar extends Foo{
protected static $stuff = 'Bar';
}
$f = new Foo();
$b = new Bar();
$f->showStuff(); // Output: Foo
$b->showStuff(); // Output: Bar
?>
You can override them, but you cannot get the value from the parent class. Well, this is wat PHP calls overriding, while it actually reintroduces the variable and tries to hide the parent variable. That's why this won't work the way you want.
Since you're not on 5.3 yet, I think the best solution is to use (and override) a static function too. If you don't need to modify the value, you can just make the class override the function to let it return a different constant value per class. If you do need the variable, you can reintroduce both the variable and the function in each class.
class x
{
static $a = '1';
static function geta()
{
return self::$a;
}
}
class y extends x
{
static $a = '2';
static function geta()
{
return self::$a;
}
}
echo x::geta();
echo y::geta();
It is dirty, but it solves the problem until you can use the neater static::
way of PHP 5.3.
There is a better solution. You can use get_called_class()
to find the current context and use that to access statics.
eg.
class Foo {
protected static $table = "foo";
static function getTable() {
$class = get_called_class();
return $class::$table;
}
}
class Bar extends Foo {
protected static $table = "bar";
}
echo Foo::getTable()."<br />\n";
echo Bar::getTable()."<br />\n";
You will get output as follows:
foo<br />
bar<br />
That will work in any PHP 5 version
Actually you can override them :)
You just can't use them in parent class, as they are static. Late static binding fixes it.
精彩评论