php – 父级是否有可能在静态方法中使用子级的常量或静态变量?

以下是我正在尝试做的一个例子.父级无法访问任何子级变量.无论我使用什么技术(静态或常量)都没关系,我只需要这样的功能.

class ParentClass
{
    public static function staticFunc()
    {
        //both of these will throw a (static|const) not defined error
        echo self::$myStatic;
        echo self::MY_CONSTANT;
    }
}

class ChildClass extends ParentClass
{
    const MY_CONSTANT = 1;
    public static $myStatic = 2;
}

ChildClass::staticFunc();

我知道这很糟糕,但我没有使用5.3.任何涉及eval的hacky解决方案都非常受欢迎.

最佳答案 编辑:< 5.3写入回复后添加了要求.在这种情况下,
debug_backtrace存在一个hacky解决方案.玩得开心.

并且,只是为了确定…我想回声ParentClass :: $myStatic;是不可能的.我再次努力为此找到一个用例.找到只能使用另一个类调用的静态方法肯定是深奥的.这是一种卑鄙的抽象方法.

原版的:

是的,late static bindings

<?php
class ParentClass
{
    public static function staticFunc()
    {
        echo static::$myStatic;
        echo static::MY_CONSTANT;
    }
}

class ChildClass extends ParentClass
{
    const MY_CONSTANT = 1;
    public static $myStatic = 2;
}

ChildClass::staticFunc(); //21
/* the next statement gives fatal error: Access to undeclared static
 * property: ParentClass::$myStatic */
ParentClass::staticFunc();

我会说这不是一个很棒的设计.如果ParentClass还定义了静态属性和常量,那将更有意义.

PHP 5.3中引入了此功能.

点赞