What is the purpose of interfaces in php?

interface, php

Solution

What you're asking for is only possible with a statically typed language, and since PHP is dynamically typed, the short answer is that it's not possible.

For example, in Java, `createMyInterface` could return an `IMyInterface`, and the only possible operations on this object are those defined in the interface itself. Of course, the object is really of type `ConcreteImplOfMyInterface`, so you can always cast it to that type to access the other fields/methods.

PHP has no declared types, so what you return from a function is simply a "variable" -- it has no type. And because there are no types, all field/method lookups are dynamic, so anything that is "there" in the object can always be accessed.

In a way, interfaces are indeed somewhat limited in use in a language such as PHP -- any class that implements an interface must implement all its methods, but since there is no guarantee as to what a function can return in the first place, there is essentially no guarantee of anything at all. The best you can do is to use `instanceof` to check whether an unknown variable implements a given interface.

Problem

If I define an interface in PHP, and a factory class that creates an instance of that interface, is there any way I can force client code to only use the interface and not the underlying concrete class? From my understanding, the clients are able to actually use any public functions/fields in the underlying class as well. Here is an example: ``` <?php interface IMyInterface { public function doSomething(); } ?> <?php class ConcreteImplOfMyInterface implements IMyInterface { const NotPartOfInterface = 'youcantseeme'; public function doSomething() { } } ?> <?php class MyInterfaceFactory { public static function createMyInterface() { return new ConcreteImplOfMyInterface(); } } ?> <?php function client() { $myInterface = MyInterfaceFactory::createMyInterface(); return $myInterface::NotPartOfInterface; } ?> ```

Original source