簡體   English   中英

如何在沒有子類調用的情況下在父類中自動運行構造

[英]How to Auto-run construct in parent class without call from child class

我正在尋找一種從子類自動神奇地調用父類構造函數(?)的方法:

(注意:這只是一個示例,因此可能存在輸入錯誤)

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 ); } __construct( $args ) { parent::__construct( $args ); }

問題:這可能嗎? 如果是這樣:怎么樣?

謝謝!

在您的示例代碼中,myParent :: __構造將被稱為wen instanciating myChild。 要讓代碼按照您的意願工作,只需更改即可

public function get_stuff( $args )
{
    $my_child = new myChild();
    print_r( $my_child->do_stuff( $args ) );
}

通過

 public function get_stuff( $args )
    {
        $my_child = new myChild($args);
        print_r( $my_child->do_stuff() );
    }

只要myChild沒有構造函數 ,就會調用/繼承父構造函數。

由於Child沒有構造函數並且擴展了 Parent ,因此只要指定了new Child()就會隱式調用Parent構造函數。

如果確實指定了Child構造函數,則必須使用指定parent::__construct(); Child構造函數中,因為它不會被隱式調用。

注意在子類中定義構造函數時,最好在方法定義的第一行調用parent::__construct() ,以便在子類啟動之前設置任何實例參數和繼承的狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM