PHP接口
PHP接口(interface)作用类似于继承中的父类,接口是用于给其他的类继承用的,但是接口中定义的方法都是没有方法体的且定义的方法必须是公有的。
举例:
<?php
interface iTemplate{ public function eat($food); public function learn($code);
} class student implements iTemplate{ public function eat($food){ echo "student eat {$food}";
} public function learn($code){ echo "student learn {$code}";
}
}
$student = new student();
$student->eat('apple'); echo '<br />';
$student->learn('PHP');?>输出:
student eat apple student learn PHP
接口中除了方法也是可以定义属性的,但必须是常量。
<?php
interface iTemplate{ public function eat($food); public function learn($code); const A='我是常量';
} class student implements iTemplate{ public function eat($food){ echo "student eat {$food}";
} public function learn($code){ echo "student learn {$code}";
} public function changliang(){ echo ITemplate::A;
}
}
$student = new student();
$student->eat('apple'); echo '<br />';
$student->learn('PHP'); echo '<br />';
$student->changliang();?>输出:
student eat apple student learn PHP 我是常量
那么既然是定义给其他类使用,就存在继承的问题,接口是可以多继承的。
举例:
<?php
interface iTemplate1{ public function eat($food);
} interface iTemplate2{ public function learn($code);
} class student implements iTemplate1,iTemplate2{ public function eat($food){ echo "student eat {$food}";
} public function learn($code){ echo "student learn {$code}";
}
}
$student = new student();
$student->eat('apple'); echo '<br />';
$student->learn('PHP');?>输出:
student eat apple student learn PHP
这样就在student类中继承了iTemplate1和iTemplate2接口,话可以先让iTemplate2接口继承iTemplate1接口,再让student类去继承iTemplate1接口,实现的效果同上。
举例:
<?php
interface iTemplate1{ public function eat($food);
} interface iTemplate2 extends iTemplate1{ public function learn($code);
} class student implements iTemplate2{ public function eat($food){ echo "student eat {$food}";
} public function learn($code){ echo "student learn {$code}";
}
}
$student = new student();
$student->eat('apple'); echo '<br />';
$student->learn('PHP');?>输出:
student eat apple student learn PHP
总结一下:
接口不能实例化
接口中的方法不能有方法体
继承接口的方法必须实现接口中的所有方法
一个类可以继承多个接口
接口中的属性必须是常量
接口中的方法必须是public(默认public)
不对的地方还望dalao们指正。
原文出处:https://www.cnblogs.com/Timesi/p/9546193.html
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦