Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP cannot override protected static

Tags:

php

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{
    protected 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
?>
like image 901
Pwnna Avatar asked May 28 '11 23:05

Pwnna


2 Answers

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
?>
like image 61
lonesomeday Avatar answered Sep 29 '22 02:09

lonesomeday


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.

like image 27
GolezTrol Avatar answered Sep 29 '22 02:09

GolezTrol