[英]How can I access a parent method within a child class in PHP?
In PHP, how do I access a parent method from within a child class? 在PHP中,如何从子类中访问父方法? The method I want to access is an instance method too.
我要访问的方法也是实例方法。 I have tried accessing with $this but of course that refers to the class I'm currently in. I don't want to have to duplicate code and don't want to access it statically.
我尝试使用$ this进行访问,但是当然是指我当前所在的类。我不想重复代码,也不想静态访问它。
Parent class: 家长班:
protected function getSearchTerm(){
return $this->searchTerm;
}
Child class: 子班:
protected function getSearchTerm(){ return parent::getSearchTerm(); }
To call a method from the parent-class within a child-class, you can use parent
: 要从子类中的父类调用方法,可以使用
parent
:
class Base
{
function somefunc()
{
echo "hello";
}
}
class Derived extends Base
{
function call_somefunc()
{
parent::somefunc();
}
}
$class = new Derived;
$class->call_somefunc(); //prints "hello"
This does work for different instances, meaning that parent::somefunc()
calls the method in the parent class of a specific instance of Derived
. 这确实适用于不同的实例,这意味着
parent::somefunc()
调用Derived
的特定实例的父类中的方法。 So basically: 所以基本上:
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.