下面是我正在尝试做的一个例子。父级无法访问任何子级变量。无论我使用什么技术(静态或常量)都没关系,我只需要这样的功能。
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解决方案都非常受欢迎。
答案 0 :(得分:2)
编辑:< 5.3写入回复后添加了要求。在这种情况下,debug_backtrace
存在一个hacky解决方案。玩得开心。
而且,只是为了确定......我认为echo ParentClass::$myStatic;
是不可能的。我再次努力为此找到一个用例。找到这样一种静态方法肯定是深奥的,这种方法只能 使用另一个类来调用。这是一种混淆的抽象方法。
ORIGINAL:
<?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中引入的。
答案 1 :(得分:0)
在5.3之前你可以用它来获得常数:
constant(get_class($this) . '::CONSTANT_NAME')