字符串未返回

时间:2014-03-20 00:06:56

标签: php oop object

我试图访问父类以将信息从其传递给其子级,然后将该信息回显给该页面,但我似乎无法让$flavor从{Soda回显出来1}}我创建的类。什么得到回应的屏幕是; Product Name: Space Juice Soda Flavor: - 我的__construct(我认为)显然在Soda课程中出现了问题,但无法弄清楚是什么。

class Product {

public $name = 'default_name';
public $price = 0;
public $desc = "default description";

function __construct($name, $price, $desc) {
    $this->name = $name;
    $this->price = $price;
    $this->desc = $desc;
}

public function getInfo() {
    return "Product Name: " . $this->name;
}
}

class Soda extends Product {

public $flavor;

function __construct($name, $price, $desc, $flavor) {
    parent::__construct($name, $price, $desc);
}

public function getInfo() {
    return "Product Name: " . $this->name . " Flavor: " . $this->flavor;
}
}

$shirt = new Product("Space Juice T-Shirt", 20, "Awesome Grey T-Shirt");
$soda = new Soda("Space Juice Soda", 2, "Thirst mutilator", "Grape");

echo $soda->getInfo();

2 个答案:

答案 0 :(得分:2)

您缺少在构造函数中分配$flavor

function __construct($name, $price, $desc, $flavor) {
    parent::__construct($name, $price, $desc);
    $this->flavor = $flavor;
}

答案 1 :(得分:1)

您没有在Soda课程中初始化flavor

class Soda extends Product {

       public $flavor;

       function __construct($name, $price, $desc, $flavor) {
           parent::__construct($name, $price, $desc);
           $this->flavor = $flavor; // add this line here <<<<<<<<<<<<<
       }
       ...