简体   繁体   English

PHP5中接口有什么好处?

[英]What are the benefits of Interface in PHP5?

As you know, we can use Interface and Implements in PHP5. 如您所知,我们可以在PHP5中使用Interface和Implements。 I used Interface in Java SE but It's useful there only for listener or ... but I can't find any benefit of Interface in PHP5. 我在Java SE中使用了接口,但它仅对侦听器或...有用但我在PHP5中找不到接口的任何好处。

Please help me understand benefits of Interface in PHP5. 请帮助我了解PHP5中界面的好处。

Thanks for your advice. 谢谢你的建议。

In an object oriented language you can't deny the benefits of Interface, there are hundreds of benefits. 在面向对象语言中,您不能否认Interface的好处,有数百种好处。

Let me give you an example for Dummies : 让我举个傻瓜的例子:

I assume you use MVC and Ajax. 我假设您使用MVC和Ajax。 And during every focusout of input you pass the input value to the server as well as a model name which is stored in the data-model (custom) attribute. 在每次input focusout ,您都会将input值传递给服务器以及存储在data-model (自定义)属性中的模型名称。

<input name="myfield" value="myvalue" data-model="user_model" onblur="send ajax request .." />

Now when you lost focus from the input it sends data to server like this 现在,当您从输入中失去焦点时,它会像这样将数据发送到服务器

{"a_model":"user_model","a_name":"myfield","a_value":"myvalue"}

In the server you just call the model name which is received from ajax request. 在服务器中,您只需调用从ajax请求接收的型号名称。 Something like this 像这样的东西

$this->{$a_model}->update($a_field,$a_value);

Here the value of $a_model varies, so you can't make sure that this model would have update() method. 这里$a_model的值$a_model有所不同,因此您无法确保此模型具有update()方法。 Here interface comes into play. 界面开始发挥作用。 Interface forces all the implemented models(classes) to have an update() method so that you can run above code unconditionally . 接口强制所有已实现的模型(类)具有update()方法,以便您可以无条件地运行上面的代码

Hope this makes sense. 希望这是有道理的。

One example. 一个例子。
I work with a remote team, they build a system that I need it to interface with mine. 我与一个远程团队合作,他们构建了一个我需要它与我的接口的系统。
I can write a complex document or just send them an interface file and tell them they must implement that interfac(es) in what they develop. 我可以编写一个复杂的文档,或者只是发送一个接口文件,并告诉他们必须在他们开发的内容中实现这个接口。

btw use of interfaces is language agnostic, mostly. btw使用接口主要是语言无关的。 The concepts are the same throughout. 这些概念贯穿始终。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM