首页 > Web开发 > 详细

PHP--继承

时间:2017-07-16 19:11:18      阅读:253      评论:0      收藏:0      [点我收藏+]

 继承使用关键字: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();

 

PHP--继承

原文:http://www.cnblogs.com/hu48986/p/7191212.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!