简体   繁体   中英

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() { ... }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM