<?php class Goods //基类Goods { private $name; private $price; protected function __construct($name2,$price2) { $this->name = $name2; $this->price = $price2; } public function showInfo() { $str = '产品的名称是:'.$this->name; $str .= '<br>产品的价格是:'.$this->price; return $str; } } class Computer extends Goods //电脑类继承Goods类 { private $color;//电脑类的新的属性 private $cpu;//电脑类的新的属性 public function __construct($name2,$price2,$color2,$cpu2) { parent::__construct($name2,$price2);//给父类的name price赋值 用parent调用父类 $this->color = $color2;//正常赋值 $this->cpu = $cpu2;//正常赋值 } public function showInfo()//调用 { $str = parent::showInfo();//调用父类的方法 $str .= '<br>颜色是:'.$this->color; $str .= '<br>cpu的型号是:'.$this->cpu; return $str; } } $computer = new Computer('联想',4600,'黑色','M-skr'); echo $computer->showInfo();
继承父类后,子类可以用父类的所有东西,可以大展拳脚.释放自己