Is it possible for a parent to use a child's constant or static variables from inside a static method?
Below is an example of what I'm trying to do. The parent can't access any of the child's variables. It doesn't matter what technique I use (static or constant开发者_JAVA百科s), I just need some kind of functionality like this.
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();
I know this sucks, but I am not using 5.3. Any hacky solution that involves eval is more than welcome.
EDIT: The < 5.3 requirement was added after the response was written. In this case, a hacky solution exists with debug_backtrace
. Have fun.
And, just to be sure... I suppose echo ParentClass::$myStatic;
is out of question. Again, I struggle to find a use case for this. It's certainly esoteric to find such a static method that would only be called using another class. It's a kind of bastardized abstract method.
ORIGINAL:
Yes, with 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();
I would say it's not a great design though. It would make more sense if ParentClass also defined the static property and the constant.
This feature was introduced in PHP 5.3.
Before 5.3 you can use this to get the constant:
constant(get_class($this) . '::CONSTANT_NAME')
精彩评论