簡體   English   中英

如何在PHP的子類中訪問父方法?

[英]How can I access a parent method within a child class in PHP?

在PHP中,如何從子類中訪問父方法? 我要訪問的方法也是實例方法。 我嘗試使用$ this進行訪問,但是當然是指我當前所在的類。我不想重復代碼,也不想靜態訪問它。

家長班:

    protected function getSearchTerm(){
    return $this->searchTerm;
}

子班:

protected function getSearchTerm(){ return parent::getSearchTerm(); }

要從子類中的父類調用方法,可以使用parent

class Base
{
    function somefunc()
    {
        echo "hello";
    }
}
class Derived extends Base
{
    function call_somefunc()
    {
        parent::somefunc();
    }
}

$class = new Derived;
$class->call_somefunc(); //prints "hello"

這確實適用於不同的實例,這意味着parent::somefunc()調用Derived的特定實例的父類中的方法。 所以基本上:

class Base
{
    function somefunc($id)
    {
        echo 'hello ' . $id . "<br />\n";
    }
}
class Derived extends Base
{
    public $id;
    function __construct($id)
    {
        $this->id = $id;
    }
    function call_somefunc()
    {
        parent::somefunc($this->id);
    }
}
$class1 = new Derived(1);
$class2 = new Derived(2);
$class1->call_somefunc(); //prints: hello 1
$class2->call_somefunc(); //prints: hello 2

暫無
暫無

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

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