且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PHP的接口方法声明

更新时间:2023-10-23 08:28:04

您错过了使用界面的重点。一个类可以有自己的方法而不实现任何接口。除了它自己的方法之外,如果它还实现了其他接口,那么它必须包含并提供这些接口中指定的所有方法的实现细节。通过这种方式,接口提供了一组通用方法,类似类型的类被签约以实现它们。作为类比,类似的建筑类别,如住宅,办公室,教室,必须有自己的方式来打开和关闭灯光。为了确保这些建筑物的建造者不要忘记实施这些方法,他们必须签署一份合同(接口),该合同规定他们必须实施两种方法,称为turnOn()和turnOff()来打开和关闭灯光。但是,遗漏了如何操作的细节。

更多示例 PHP:对象接口 - 手册 [ ^ ]

PHP object interface. I have understood the all methods declared in an interface must be public. but for example if i have 10 public methods in my base class which implements interface did i need to add all 10 into the interface delcaration.

What I have tried:

If the answer is "NO" then what type of methods should i need to declare into interface.

You are missing the point of using an interface. A class can have its own methods without implementing any interfaces. Apart from its own methods, if it also implements other interfaces, then it has to include and provide implementation details for all the methods specified in those interfaces. In this way, an interface provides a set of common methods that classes of a similar type are contracted to implement them. As an analogy, similar classes of building such as residence, office, clas-s-room must have their own ways to turn on and off the light. To make sure that the builders of such buildings not to forget to implement these methods, they have to sign a contract (interface) which states that they must implement two methods called say turnOn() and turnOff() to turn on and off the light, however leaving out the details of how to do it.
More example PHP: Object Interfaces - Manual[^]