php中的接口interface

时间:2023-03-08 19:31:21
php中的接口interface
* 接口
* 1.使用关键字:interface
* 2.类是对象的模板,接口是类的模板
* 3.接口看作是一个特殊的类
* 4.接口中的方法,只声明不实现,与抽象类一样
* 5.接口中的方法必须是public,支持static
* 6.接口中可以声明类常量const,但不允许被类或子接口覆盖
* 7.用类实现一个接口使用implements 关键字
* 8.一个类可以实现多个接口,多个接口之间用逗号分开
* 9.接口之间也可以使用关键字extends继承
* 10.一个类实多个接口时,方法不可以重名 //声明接口:动物
if (!interface_exists('Animal')) {
interface Animal
{
//接口常量
const status = 'viable'; //能存活的
//接口方法:饲养时吃什么
public function feeding($foods);
}
}
//声明类Cat,并实现接口Animal
if (interface_exists('Animal')) {
class Cat implements Animal
{
private $name = '猫';
//在类中必须实现接口中的方法feeding()
public function feeding($foods)
{
return $this->name.'吃'.$foods;
}
}
}
//实例化Cat类,
echo (new Cat())->feeding('老鼠');
echo '<hr>';
//再定义一个接口:动物的特性
if (!interface_exists('Feature')) {
interface Feature
{
//接口方法
public function hobby($hobby);
}
}

//声明一个类Dog,实现了二个接口: Animal,Feature
if (interface_exists('Animal') && interface_exists('Feature')) {
class Dog implements Animal, Feature
{
private $name = '狗';
//必须实现接口Animal中的feeding()方法
public function feeding($foods)
{
// return $this->name.'吃'.$foods;
//改成链式
echo $this->name.'吃'.$foods;
return $this;
}
//必须实现接口Feature中的hobby()方法
public function hobby($hobby)
{
// return $hobby;
//改成链式
echo $hobby;
return $this;
}
}
}
//实例化Dog类
echo (new Dog())->feeding('肉');

echo (new Dog())->hobby('忠诚,勇敢,不离不弃~~');
//大家想想如何将上面的二个方法调用改成链式?
//注意:先把上面的实例化调用语句注释掉,否则下面的链式调用不生效
(new Dog)->feeding('骨头')->hobby(',可爱,温顺,听话~~');