代码之家  ›  专栏  ›  技术社区  ›  ryeguy

父级是否可以从静态方法内部使用子级的常量或静态变量?

  •  4
  • ryeguy  · 技术社区  · 14 年前

    下面是我要做的一个例子。父级无法访问子级的任何变量。不管我使用什么技术(静态或常量),我只需要这样的一些功能。

    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的黑客解决方案都是受欢迎的。

    2 回复  |  直到 11 年前
        1
  •  2
  •   Artefacto    14 年前

    编辑:在编写响应之后添加了<5.3要求。在这种情况下,黑客解决方案存在于 debug_backtrace . 玩得高兴。

    而且,只是为了确定…我想 echo 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中引入的。

        2
  •  0
  •   Michael    11 年前

    在5.3之前,你可以用这个来得到常数:

    constant(get_class($this) . '::CONSTANT_NAME')