类的继承和接口的实现

<?php 
header('Content-type:text/html;charset=utf8');
class Monkey{
	public $name;
	public function __construct($name){
		$this->name = $name;
	}
	public function climbing(){
		echo '<br>'.$this->name.'会爬树';
	}
}
interface iBirdable{
	public function flying();
}
interface iSwimable{
	public function swimming();
}
//继承Monkey类,实现iBirdable和iSwimable接口
class LittleMonkey extends Monkey implements iBirdable,iSwimable{
	public function flying(){
		echo '<br>'.$this->name.'通过学习,学会飞翔';
	}
	public function swimming(){
		echo '<br>'.$this->name.'通过学习,学会游泳';
	}
}
$littlemonkey = new LittleMonkey('小悟空');
$littlemonkey->climbing();
$littlemonkey->swimming();
$littlemonkey->flying();
class SuperMonkey extends LittleMonkey{}
$superMonkey = new SuperMonkey('超级猴子');
$superMonkey->climbing();
$superMonkey->flying();
$superMonkey->swimming();
?>

总结:

(1)实现接口可以看做是对php单继承机制的补充,因为php是单继承。

(2)实现接口可以在不打破继承的层级关系的前提下,对类的功能进行扩展。

猜你喜欢

转载自blog.csdn.net/wangyingjie290107/article/details/79946595