【问题标题】:Prevent late static binding with static variable access from parent function防止后期静态绑定与来自父函数的静态变量访问
【发布时间】:2013-01-23 08:04:35
【问题描述】:

给定以下类层次结构:

class ParentClass {
    private static $_test;

    public function returnTest() {
        return static::$_test;
    }
}
class ChildClass extends ParentClass {
    // intentionally left blank
}
$child = new ChildClass();
echo $child->returnTest();

生成的输出是以下错误消息:
Fatal error: Cannot access property ChildClass::$_test
有没有办法防止后期静态绑定发生?由于我正在调用未覆盖的父类的函数,因此我觉得应该允许我执行上述操作。

【问题讨论】:

    标签: php late-static-binding


    【解决方案1】:

    使用return self::$_test 而不是return static::$_test

    这确保您访问定义returnTest 的类的字段$_test

    参考http://www.php.net/manual/en/language.oop5.late-static-bindings.php

    【讨论】:

    • 像 Mathieu Imbert 建议的那样调用 ParentClass::$_test 和调用 self::$_test 有什么区别?
    • 从技术上讲,没有:结果是一样的。我想这是一个品味问题,你是否想明确地重复类名。顺便说一句,用 PHP 文档的链接编辑了我的答案。
    【解决方案2】:

    您正在从实例化类调用静态属性。只需使用类的名称:

    return static::$_test;
    

    【讨论】:

      猜你喜欢
      • 2013-01-31
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      相关资源
      最近更新 更多