PHP--继承

 继承使用关键字:extends
 PHP是单继承,有且只有一个父类
 PHP的构造函数可以被继承,但是如果子类也定义了构造函数,则父类的被覆盖

子类中将父类的函数进行重新的定义,叫重写

 

 parent 关键字,本意为父母,当前在子类中指代当前类的父类的对象,
使用它可以调用被覆盖了的父类的属性和行为

class Animal{

public $name;
public $sex;
public $age;

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

public function shout(){
echo '动物都有各自的叫声';
}

public function desc(){

}
}
class Dog extends Animal{

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

/**
* 子类中将父类的函数进行重新的定义,叫重写
*/
public function shout(){

echo ',狗狗的叫声:汪~~汪~~汪~';
}

public function desc(){
echo '狗狗的名字:'.$this->name;
// parent::shout();
$this->shout();
}
}
class Cat extends Animal{

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

public function shout(){
echo ',猫咪的叫声:喵~~呜~喵~~呜~';
}
public function desc(){
echo '喵咪的名字:'.$this->name;
$this->shout();
}
}

$animal = new Dog('来福');
$animal->desc();

echo '<br><br>';

$animal = new Cat('咪咪');
$animal->desc();

 

posted @ 2017-07-16 17:55  胡川云  阅读(270)  评论(0编辑  收藏  举报