我有一个类层次结构,如下所示:
class Alpha {
public function initialize() {
$class = get_class($this);
$family = array( $class );
while( ($class = get_parent_class($class)) !== false ) {
$family[] = $class;
}
$family = array_reverse($family);
foreach($family as $className) {
// call $className's start (instance) method
}
}
public function start() {
echo "calling start from Alpha\n";
}
}
class Beta extends Alpha {
public function start() {
echo "calling start from Beta\n";
}
}
class Charlie extends Beta {
public function start() {
echo "calling start from Charlie\n";
}
}
$c = new Charlie();
$c->initialize();
Alpha 的 initialize 方法应该调用派生类的 start 方法以及所有派生类的祖先类的 start 方法,一直到 Alpha 的 start 方法。该代码应产生以下输出:
calling start from Alpha
calling start from Beta
calling start from Charlie
但是,我似乎无法弄清楚如何调用 $className 变量指定的特定祖先类的实例方法。
我使用过call_user_func(array($className, 'start'))
,但这会导致 start 方法被视为静态函数。有任何想法吗?