Home > Backend Development > PHP Tutorial > Introduction to PHP class and object interface definitions and detailed explanations of usage examples

Introduction to PHP class and object interface definitions and detailed explanations of usage examples

伊谢尔伦
Release: 2023-03-12 13:20:01
Original
1779 people have browsed it

Implementation of interface

<?php
//interface 关键字用于定义一个接口
interface ICanEat{
       //接口里面的方法不需要实现
       public function eat($food);
}
//implements关键字用于类实现某个接口
class Human implements ICanEat{
       //实现了接口后,必须提供接口中方法的具体实现
       public function eat($food){
       echo "Human eating".$food;
    }

}

?>
Copy after login

Then after this definition

by instantiating the object

$peroson1=new Human();

$person1->eat('apple');

The output result is

Human eating apple

<?php
//interface 关键字用于定义一个接口
interface ICanEat{
       //接口里面的方法不需要实现
       public function eat($food);
}
//implements关键字用于类实现某个接口
class Human implements ICanEat{
       //实现了接口后,必须提供接口中方法的具体实现
       public function eat($food){
       echo "Human eating".$food."\n";
    }

}
$person1 = new Human();
$person1->eat(&#39;apple&#39;);

//我们可以通过instanceof关键字来判断对象是否实现了某个接口

var_dump($person1 instanceof ICanEat);

//在上面的例子中我们可以通过这个关键字来判断是否实现了ICanEat这个接口

?>
Copy after login

Then the output The result should be

Human eating apple

Bool (true)

<?php
//interface 关键字用于定义一个接口
interface ICanEat{
//接口里面的方法不需要实现
public function eat($food);
}
//implements关键字用于类实现某个接口
class Human implements ICanEat{
//实现了接口后,必须提供接口中方法的具体实现
public function eat($food){
echo "Human eating".$food."\n";
}
}
$person1 = new Human();
$person1->eat(&#39;apple&#39;);
//我们可以通过instanceof关键字来判断对象是否实现了某个接口
var_dump($person1 instanceof ICanEat);
//在上面的例子中我们可以通过这个关键字来判断是否实现了ICanEat这个接口
 
//类可以继承,那么接口同样也能被继承
interface ICanSleep extends ICanEat{
  public function sleep();
}
//当类实现子接口,那么父接口定义的方法也需要在类中来具体实现
class Human1 implements ICanSleep{
  public function eat($food){}
  public function sleep(){}
}
?>
Copy after login

The above is the detailed content of Introduction to PHP class and object interface definitions and detailed explanations of usage examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template