我在尋找一種方法來調用父類的構造從子類自動神奇(?):如何在父類中自動運行結構,而不調用從子類
(注:這僅僅是一個例子,所以輸入錯誤可能存在)
Class myParent()
{
protected $html;
function __construct($args)
{
$this->html = $this->set_html($args);
}
protected function set_html($args)
{
if ($args['foo'] === 'bar')
$args['foo'] = 'foobar';
return $args;
}
}
Class myChild extends myParent
{
public function do_stuff($args)
{
return $this->html;
}
}
Class myInit
{
public function __construct($args)
{
$this->get_stuff($args);
}
public function get_stuff($args)
{
$my_child = new myChild();
print_r($my_child->do_stuff($args));
}
}
$args = array('foo' => 'bar, 'what' => 'ever');
new myInit($args);
// Should Output:
/* Array('foo' => 'foobar', 'what' => 'ever') */
我想避免由具有調用(內側類myChild)__construct($args) { parent::__construct($args); }
。
問題:這可能嗎?如果是這樣:如何?
謝謝!
你爲什麼反對調用'parent :: __ construct()'? – cspray
我想PHP也奇蹟般地寫我的應用程序。 –
@Wesley van Opdorp請參閱解決方案。適用於我。 @Charles Sprayberry我有一個基類,它被未知數量的子類所擴展,因此我必須爲所有輸入參數運行標準程序(例如,丟棄無效輸入,解析默認值等)。 – kaiser