Php 使用接口空方法和对单个普通类的多重继承
与在接口中一样,只指定了一个方法,而没有如下代码Php 使用接口空方法和对单个普通类的多重继承,php,oop,inheritance,interface,multiple-inheritance,Php,Oop,Inheritance,Interface,Multiple Inheritance,与在接口中一样,只指定了一个方法,而没有如下代码 interface eat { public function ways_of_eating_food($givingsomefood); } //and remaining class does is only access the method whats the use of it as they could manually create it in the class to class human implements eat
interface eat {
public function ways_of_eating_food($givingsomefood);
}
//and remaining class does is only access the method whats the use of it as they could manually create it in the class to
class human implements eat {
public function ways_of_eating_food($foodtoeat){
This is how people eat the food//
}
}
class animal implements eat {
public function ways_of_eating_food($foodtoeat){
//this is how animal eat the food
}
}
由于动物和人类是两个不同的类,其核心部分是相同的,即它们确实吃给定的食物,但风格不同,所以这实际上是有用的,接口如何支持多重继承?接口对于数据隐藏是有用的。假设您想为某些客户机代码提供一个类,但不想授予它们完全访问权限。在不限制类功能的情况下限制访问的一种方法是实现一个接口,并要求客户端代码通过工厂获取对象 接口的另一个好处是团队开发。如果有十几个程序员在处理需要连接的不同代码段,那么最好为连接定义接口。只要程序员按照接口进行编写,无论个人选择和风格如何,一切都会很好地联系在一起 还有一个好处是,对于接口,您可以使用类,而无需先定义它。例如,如果您有一个类,它完成了大量复杂的工作,并且在项目的其余部分之前无法完成,那么项目的其余部分可以使用它的接口,从而避免由于开发该类而陷入停滞 想象一下,你真的不知道生物可以吃什么不同的方式,但在你发现所有可能的饮食方法之前,你不想让其他类不起作用。只需声明一个接口eat,并让其他类实现它 他们确实吃给定的食物,但风格不同,那么这到底有用吗 你应该读一下。接口对于管理共享行为的对象很有用,但在运行前您不知道必须使用哪个对象 考虑一个让人吃东西的函数。由于您创建了一个接口,因此可以在函数中键入提示接口,以便它可以管理任何类型的进食生物:
function makeEat(eat $obj) { $obj->ways_of_eating_food( getFood() ); }
function getFood() { return $food; }
但是,如果您没有定义接口,那么您必须创建一个函数来让人吃,另一个函数来让猫吃,另一个函数来让狗吃,等等。这真的是不切实际的。通过使用接口和类型将其提示给函数,可以使用相同的函数执行相同的工作
接口如何支持多重继承
正如文森特所说:
PHP支持多级继承,而不是多重继承 这意味着您可以实现多个不同的接口,但不能扩展多个类
interface living { public function eat(food $food); }
interface food { public function getEnergyValue(); }
interface animal { public function breath(); }
class cow implements living, animal
{
private $energy = 0;
private $secondsRemaining = 10;
public function eat(food $food) { $this->energy += $food->getEnergyValue(); }
public function breath() { $this->secondsRemaining += 10; }
}
class salad implements food
{
private $value = 50;
public function getEnergyValue() { return $this->value; }
}
$bob = new cow();
$bob->eat(new salad());
PHP的可能副本不支持多级继承,而不是多重继承。这意味着你不能有一个类继承了另外两个类。。。我不确定我是否同意副本。理论是正确的,但代码示例并没有明确说明如何实际使用它们。