Class a {
public function __construct($a){
$this->age = $a;
}
}
Class b extends a {
public function printInfo(){
echo 'age: ' . $this->age . "\n";
}
}
$var = new b('age');
$var->printInfo();
我理解这段代码是如何工作的,但是可以将参数传递给类和父类的构造函数吗?
我的下面尝试导致错误
Class a {
public function __construct($a){
$this->age = $a;
}
}
Class b extends a {
public function __construct($name){
$this->name = $name;
}
public function printInfo(){
echo 'name: ' . $this->name . "\n";
echo 'age: ' . $this->age . "\n";
}
}
$var = new b('name', 'age');
$var->printInfo();
?>
答案 0 :(得分:3)
是的,您只需使用parent::__construct()
方法。
像这样:
class a{
/**
* The age of the user
*
* @var integer
*/
protected $age;
function __construct($a){
$this->age = $a;
}
}
class b extends a{
/**
* The name of the user
*
* @var string
*/
protected $name;
function __construct($name,$age){
// Set the name
$this->name = $name;
// Set the age
parent::__construct($age);
}
public function printInfo(){
echo 'name: ' . $this->name . "\n";
echo 'age: ' . $this->age . "\n";
}
}
$var = new b('name','age');
$var->printInfo();
只需确保将变量设置为公开或受保护!
答案 1 :(得分:0)
您可以将值传递给父构造函数,但是您的工作方式是错误的,
$var = new b('name', 'age');
就好像子类在其构造函数中接受两个参数,但实际上它只有一个参数。
您可以将参数传递给父构造函数,例如
parent::__construct($var);
所以将你的b级改为
Class b extends a {
public function __construct($name, $age){
$this->name = $name;
parent::__construct($age);
}
public function printInfo(){
echo 'name: ' . $this->name . "\n";
echo 'age: ' . $this->age . "\n";
}
}
答案 2 :(得分:0)
是的,您可以将参数传递给类以及父类
Class a {
public function __construct($age){
$this->age = $a;
}
}
Class b extends a {
public function __construct($name,$age){
parent::__construct($age);
$this->name = $name;
}
}
$var = new b('name', 'age');
?>
答案 3 :(得分:0)
只需在子项中调用parent :: __ construct即可。例如
class Form extends Tag
{
function __construct()
{
parent::__construct();
// Called second.
}
}
答案 4 :(得分:0)
以下是应该如何:
<?php
class a {
private $age;
public function __construct($age){
$this->age = $age;
}
public function getAge()
{
return $this->age;
}
}
class b extends a {
private $name;
public function __construct($age, $name){
parent::__construct($age);
$this->name = $name;
}
public function printInfo(){
echo 'name: ' . $this->name . "\n";
echo 'age: ' . $this->getAge() . "\n";
}
}
$b = new b(20, "Bob");
$b->printInfo();
?>