php abstract classes and interfaces involving static methods?
Update
After the comment from @hvertous, I decided to test this out. Using 3v4l we can see that abstract public static method
:
- Works for versions 5 > 5.1.6
- Doesn't work for 5.2 > 5.6.38
- Works for 7.0.0 > 7.3.1
Which confirms that it was removed in PHP 5.2, but if you are using PHP 7+ you can once again use abstract static methods.
Original answer
Yes, abstract static methods were removed in PHP 5.2. Apparently they were an oversight. See Why does PHP 5.2+ disallow abstract static class methods?.
However, you can have static methods in an interface, see this comment on php.net.
The problem you face is that you want your implementations to have different function signatures, which means that you probably shouldn't be using inheritance to solve your problem.
In most languages, including PHP, you cannot require a class to implement static methods.
This means neither class inheritance, nor interfaces, will allow you to require all implementors define a static method. This is probably because these features are designed to support polymorphism rather than type definition. In the case of static methods you'll never have an object to resolve the type from, so would have to do ClassName::Method
explicitly, so the theory is you wouldn't gain anything from polymorphism.
As such, I see three solutions
Declaring the static methods in each class (after all, you are never going to
If you want a method to create instances of your class, but don't want to require an instance to call this method, you could create "Builder" classes to serve this purpose (e.g.
OrderBuilder
), such that you instantiate anOrderBuilder
and call theCreate
method on this object instead to getOrder
instances.(Recommended) Why aren't you simply using the
Order
constructor?
PHP 7.4+ allows to require a static method in an interface:
interface StaticInterface {
public static function interfaceMethod();
}
class MyProvider implements StaticInterface {
//public static function interfaceMethod() {}
}
Fatal error without the method: https://3v4l.org/YbA4u
No errors when implementing the method: https://3v4l.org/QNRJB