<? //parent::关键字 /** * PHP5中使用parent::来引用父类的方法。 * parent:: 可用于调用父类中定义的成员方法。 * parent::的追溯不仅于直接父类。 */ //通过parent::调用父类方法 //声明一个员工类,经理类继承自员工类 class employee{ protected $sal = 3000; public function getSal(){ $this->sal = $this->sal + 1200; return $this->sal; } } class Manager extends employee{ //如果想让经理在员工工资的基础上多发1500元 //必须先调用父类的getSal()方法 public function getSal(){ parent::getSal(); $this->sal = $this->sal + 1500; return $this->sal; } } $emp = new employee(); echo "普通员工的工资是 " . $emp->getSal(); echo "<br>"; $manager = new Manager(); echo "经理的工资是 " . $manager->getSal(); ?>
<? //父类的private属性 //Private属性是不能被继承的,如果父类有私有的属性。 //那么父类的方法只为父类的私有属性服务。 class employee{ private $sal = 3000; public function getSal(){ return $this->sal; } } class Manager extends employee{ protected $sal = 5000; public function getParentSal(){ //这里返回的是父类的private属性 return parent::getSal(); } } $manager = new Manager(); echo "PHP" . phpversion()."<br>"; //那么父类的方法只为父类的私有属性服务。 echo $manager->getSal(); echo "<br>"; echo "parent's \$sal ".$manager->getParentSal(); ?>
<? //如果父类中的属性被子类重写了。 class employee{ protected $sal = 3000; public function getSal(){ return $this->sal; } } class Manager extends employee{ protected $sal = 5000; public function getParentSal(){ //父类的protected属性已经被子类重写了 return parent::getSal(); } } $manager = new Manager(); echo "PHP" . phpversion()."<br>"; echo $manager->getSal(); echo "<br>"; echo "parent's \$sal ".$manager->getParentSal(); ?>
<? //子类中重写的方法对当前private有效。 class employee{ private $sal = 3000; public function getSal(){ return $this->sal; } } class Manager extends employee{ private $sal = 5000; //重写父类的方法 public function getSal(){ return $this->sal; } public function getParentSal(){ //这里返回的是父类的private属性 return parent::getSal(); } } $manager = new Manager(); echo "PHP" . phpversion()."<br>"; echo $manager->getSal(); echo "<br>"; echo "parent's \$sal ".$manager->getParentSal(); ?>