* Interface
* 1. Use the keyword: interface
* 2. Class is the template of the object, and the interface is the template of the class
* 3. Look at the interface It is a special class
* 4. The methods in the interface are only declared but not implemented, just like abstract classes
* 5. The methods in the interface must be public and support static
* 6. Class constants const can be declared in the interface, but they are not allowed to be overridden by classes or sub-interfaces
* 7. Use the implements keyword to implement an interface with a class
* 8 .A class can implement multiple interfaces, separated by commas
* 9. Interfaces can also use the keyword extends to inherit
* 10. A class can have multiple interfaces When using an interface, methods cannot have the same name
//Declare the interface: Animal
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; } } } //实例化Dog类, 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; } } }
//Instantiate the Dog class
echo (new Dog())->feeding('肉'); echo (new Dog())->hobby('忠诚,勇敢,不离不弃~~');
//Think about how to combine the above two Change a method call to a chain?
//Note: Comment out the above instantiation call statement first, otherwise the following chain call will not take effect
(new Dog)->feeding('骨头')->hobby(',可爱,温顺,听话~~');
The above is the detailed content of interface in php. For more information, please follow other related articles on the PHP Chinese website!