What you are asking for is only possible with a statically typed language, and since PHP is dynamically typed, the short answer is that this is not possible.
For example, in Java, createMyInterface
can return IMyInterface
, and the only possible operations on this object are those defined in the interface itself. Of course, the object really has the ConcreteImplOfMyInterface
type, so you can always apply it to this type to access other fields / methods.
PHP has no declared types, so what you return from a function is just a "variable" - it has no type. And since there are no types, all searches for fields / methods are dynamic, so you can always access anything that is "there" in the object.
In a sense, the interfaces are really somewhat limited in use in a language such as PHP - any class that implements the interface must implement all its methods, but since there is no guarantee that the function can return in the first place, there are essentially no guarantees at all . The best you can do is use instanceof
to check if an unknown variable implements this interface.
casablanca
source share