Heim  >  Artikel  >  Backend-Entwicklung  >  Einführung in PHP-Klassen- und Objektschnittstellendefinitionen und detaillierte Erläuterungen von Anwendungsbeispielen

Einführung in PHP-Klassen- und Objektschnittstellendefinitionen und detaillierte Erläuterungen von Anwendungsbeispielen

伊谢尔伦
伊谢尔伦Original
2017-07-03 10:52:431687Durchsuche

Implementierung der Schnittstelle

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

}

?>

Dann instanziiert

nach dieser Definition das -Objekt

$peroson1 = new Human();

$person1->eat('apple');

Das Ausgabeergebnis ist

Mensch isst Apfel

<?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这个接口

?>

Dann sollte das Ausgabeergebnis

Human eat 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(){}
}
?>

lauten

Das obige ist der detaillierte Inhalt vonEinführung in PHP-Klassen- und Objektschnittstellendefinitionen und detaillierte Erläuterungen von Anwendungsbeispielen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn