我正在实现一个简单的 oop 程序,有些事情对我来说不清楚。有人可以解释为什么它不起作用。
我有基类 - 动物和子类 - 狗。
class Animal {
public $name;
public function __construct($name)
{
$this->name = $this->getName();
}
public function getName()
{
return $this->name;
}
}
class Dog extends Animal
{
public function __construct($name)
{
parent::__construct($name);
}
public function print()
{
return "Dog name is " . $this->getName();
}
}
index.php
我测试它的文件。
$dog = new Dog('george');
echo $dog->getName();
echo $dog->print();
该程序的输出只是Dog name is
好吧,看看你的构造函数是做什么的:
public function __construct($name)
{
// you assign to $this->name the return value of $this->getName()...which at that time, is null.
$this->name = $this->getName();
}
您应该使用传递给构造函数的 $name
参数:
public function __construct($name)
{
// okay!
$this->name = $name;
}
你的 Animal 构造函数是错误的。您正在使用其吸气器设置变量...使用构造函数的参数。
派生类构造函数将$name变量发送到基类,但它从未实际将其分配给任一类的 name 属性。
尝试
public function __construct($name)
{
$this->name = $name;
}
看看这是否会改变你的输出。