gpt4 book ai didi

PHP:如何调用类层次结构中的所有同名方法?

转载 作者:行者123 更新时间:2023-12-04 18:21:34 25 4
gpt4 key购买 nike

我有一个类层次结构,如下所示:

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 方法被视为静态函数。有任何想法吗?

最佳答案

在类函数调用中,如 Classname::start 应该调用 Classname 的函数 start 而不是静态调用

class Alpha {

public $myvar = 0;

public function initialize() {

$class = get_class($this);
$family = array( $class );
while( ($class = get_parent_class($class)) !== false ) {
$family[] = $class;
$this->myvar ++;
}
$family = array_reverse($family);
foreach($family as $className) {
// call $className's start method
eval("{$className}::start();");
}
}

public function start() {
echo "{$this->myvar} calling start from Alpha\n";
}
}

class Beta extends Alpha {
public function start() {
echo "{$this->myvar} calling start from Beta\n";
}
}

class Charlie extends Beta {
public function start() {
echo "{$this->myvar} calling start from Charlie\n";
}
}

$c = new Charlie();
$c->initialize();

关于PHP:如何调用类层次结构中的所有同名方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10561306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com