我想要做的是從當前班級的父母調用每個方法「init」。從每個父母調用方法X
我這樣做是爲了避免程序員每次在新控制器中創建init方法時都必須調用init方法(parent :: init())。
例子:
class Aspic\Controller { } // main controller
class ControllerA extends Aspic\Controller { public function init() {/* do something 1 */}
class ControllerB extends ControllerA {}
class ControllerC extends ControllerB { public function init() { /* do something 2 */ }
class ControllerD extends ControllerC {}
正如你可以看到init
方法不調用父init
方法,但我想我的應用程序(有一個選項)做到這一點。
因此,當我在加載ControllerD
時,在調用它的init
方法(在示例中沒有,但應用程序測試它)之前,我想調用每個父項init
方法。
的聲音是這樣的:
parent::init(); // Controller C init
parent::parent::parent::init(); // Controller A init
,所以我做:
if($this->_autoCallParentsInit) {
// Aspic\Controller is the main controller, which is the mother of all others
$aspicControllerRc = new \ReflectionClass('Aspic\\Controller');
$rc = new \ReflectionClass($this); // We are in D
$currPrefix = '';
// Calling each init methods of current class parent
// Avoid using parent::init() in each controller
while(($parentClass = $rc->getParentClass()) AND $aspicControllerRc->isInstance($parentClass)) {
/*
$aspicControllerRc->isInstance($parentClass)
=> because Aspic\Controller extends a "Base class". Thus, we stopped at Aspic\Controller
*/
$currPrefix .= 'parent::';
// Must have explicit method (not inherited from parent) BUT actually hasMethod does not care
if($parentClass->hasMethod('init')) {
call_user_func($currPrefix.'init');
}
}
}
這是行不通的,因爲ReflectionClass::isInstance
不接受別人的說法,比我們要測試的對象(而不是ReflectionClass
代表它的實例)
** 簡單地說: 我ha有一個對象$ x,我想調用$ x的類的每個父類的init
方法。 **
這可能嗎?
我希望我是清楚的:)
感謝
試圖改進你的格式! – markus
這在網絡編輯器中並不容易:)完成 – Leto
看起來你試圖用繼承來實現某些東西,你應該把它封裝到它自己的代碼中,因爲你是沒有使用正確的工具來完成這項工作,但是很難說出自己想要的問題,所以我不能立即提出建議。 – hakre