繁体   English   中英

父 static function 调用 static 子变量

[英]Parent static function calling static child variable

这是我正在处理的类的简化版本

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

这应该在 php 版本 5.2.17 中工作还是我设置错误。 我目前收到一条错误消息,说它找不到A::$valB

需要后期 static 绑定,该绑定存在于 PHP 5.3.0 及更高版本中。

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

在 getVal 中,您需要使用return static::valB; 而不是return self::valB;

首先,您的代码语法错误。 从修复它开始:

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

现在,这将永远不会起作用,因为getVal受到保护。 除非你从A或它的一个孩子中调用它,否则它不会工作。

self关键字解析为调用它的 class。 由于selfA中使用: self == A

您将需要使用后期的 static 绑定来修复它:

return static::$valB;

最后,我建议您在A中也声明$valB以避免致命错误:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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