2

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

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

4

2 回答 2

2
class Alpha {
    public function initialize() {
        // ... call all 'start' methods in class hierarchy starting with highest level     class (Alpha's start method) and ending with lowest derived class
    }

    public function start() {
        echo "calling start from Alpha\n";
    }
}

class Beta extends Alpha {
    public function start() {
        echo "calling start from Beta\n";
        parent::start();
    }
}

class Charlie extends Beta {
    public function start() {
        echo "calling start from Charlie\n";
        parent::start();
    }

    public function initialize() {
        $this->start();
    }
}

$c = new Charlie();
$c->initialize();
于 2012-05-12T05:38:15.387 回答
2

在类函数调用中,如 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();
于 2012-05-12T07:27:15.037 回答