[英]Construct Parent class from the Child class [PHP/OOP]
I would like to do instantiate a class A and then instantiate a class B (that extends A) from the reference of Class A. 我想实例化一个类A,然后从类A的引用实例化一个类B(扩展了A)。
In other words, I have this classes: 换句话说,我有以下课程:
class A{
protected $name;
public function getName(){
return $this->name;
}
public function setName($name){
$this->name = $name;
}
public function __construct($name)
{
$this->name = $name;
}
}
class B extends A {
protected $value;
public function __construct($value){
$this->value=$value;
}
public function getValue(){
return $this->value;
}
public function setValue($value){
$this->value=$value;
}
}
And I would like to do something like : 我想做这样的事情:
$a = new ('Name in A class');
$b = new ($a, 'Value in B class');
Thank you for your answers. 谢谢您的回答。
To construct the parent class from its child you can call the parent's constructor by using a parent keyword. 要从其子级构造父类,可以使用parent关键字调用父类的构造函数。
class B extends A{
function __construct($name, $value){
parent::__construct($name);
$this->value=$value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.