父类的php调用方法不起作用

时间:2015-01-07 13:22:17

标签: php

我正在实施一个简单的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

3 个答案:

答案 0 :(得分:2)

好吧,看看你的构造函数做了什么:

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;
}

答案 1 :(得分:1)

你的Animal的构造函数是错误的。您正在使用其getter设置变量...使用构造函数的参数。

答案 2 :(得分:1)

派生类构造函数将$ name变量发送到基类,但它实际上从未将它分配给任一类的name属性。

尝试

 public function __construct($name)
{
    $this->name = $name;
}

看看是否会改变你的输出。