PHP接口(interface
)做用相似於繼承中的父類,接口是用於給其餘的類繼承用的,可是接口中定義的方法都是沒有方法體的且定義的方法必須是公有的。
舉例:php
<?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'); ?>
輸出:app
student eat apple student learn PHP
接口中除了方法也是能夠定義屬性的,但必須是常量。code
<?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'); ?>
輸出:io
student eat apple student learn PHP
這樣就在student
類中繼承了iTemplate1
和iTemplate2
接口,話能夠先讓iTemplate2
接口繼承iTemplate1
接口,再讓student
類去繼承iTemplate1
接口,實現的效果同上。
舉例:function
<?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'); ?>
輸出:class
student eat apple student learn PHP
總結一下:方法
不對的地方還望dalao們指正。im