开发者

Parent static function calling static child variable

Here's a simplfied version of the classes I'm dealing with

class A {
   static protected function getVal() {
              return self::$valB;
            }
}
class B extend A {
   static protected $valB = 'Hello';
开发者_运维百科}
B::getVal(); // Hello

Should this work in php version 5.2.17 or do I have it setup wrong. I'm currently getting an error saying that it can't find A::$valB.


Requires late static binding, which is present in PHP 5.3.0 and later.

http://us3.php.net/manual/en/language.oop5.late-static-bindings.php

In getVal, you'd want to use return static::valB; instead of return self::valB;


First, your code syntax is wrong. Start by fixing it:

class A {
   static protected function getVal() {
       return self::$valB;
   }
}
class B extends A {
   static protected $valB = 'Hello';
}
B::getVal();

Now, this will never work because getVal is protected. Unless you call it from A or one of its child, it won't work.

The self keyword resolves to the class that calls it. Since self is used in A: self == A.

You will need to use late static bindings to fix it:

return static::$valB;

Lastly, I'd recommend you also declare $valB in A to avoid fatal errors:

class A {
    static protected $valB;
    static protected function getVal() { ... }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜