Php abstract classes and interfaces using static methods?

I am trying to figure out how best to complete my classes.

my situation.

I have an abstract order class that contains the methods and order information that are needed for two child classes

order_Outbound

and order_inbound

each child class needs 2 static public methods called create and get

but from what i read about php 5.3 you have no abstract static methods.

so I thought that I should have an Order_Interface interface that takes on this role, but how do I implement it. I am still implementing it in the parent class

and in this case, the parent abstract class still requires me to create a get and create method in the abstract class. or am I implementing it in children and expanding from an abstract class ???

ALSO!!! both outgoing and incoming children require the creation of a static method, but require the transfer of different parameters

can i in the interface the public static function create ()

and in its implementation in order_outbound declares a public static function create ($ address, $ reference, $ orderID)

+6
source share
2 answers

In most languages, including PHP, you cannot require the class to implement static methods.

This means that neither class inheritance nor interfaces will allow you to require that all developers define a static method. This is likely due to the fact that these functions are designed to support polymorphism, and not type determination. In the case of static methods, you will never have an object for type resolution, so you would have to do ClassName::Method explicitly, so the theory is that you will not get anything from polymorphism.

So I see three solutions

  • Declaring static methods in each class (after all, you'll never

  • If you want to instantiate your class, but do not want the instance to call this method, you could create β€œBuilder” classes for this purpose (for example, OrderBuilder ), so you create an instance of OrderBuilder and call the Create method on this object instead to get instances of Order .

  • (recommended) Why aren't you just using the Order constructor?

+6
source

Refresh

After a comment from @hvertous, I decided to check it out. Using 3v4l, we can see this abstract public static method :

  • Works on version 5> 5.1.6
  • Does not work for 5.2> 5.6.38
  • Works on 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 use abstract static methods again.

Original answer

Yes, abstract static methods have been removed in PHP 5.2. Apparently they were an oversight. See Why PHP 5. 2+ prohibits abstract methods of a static class? ,

However, you can have static methods in the interface, see this comment on php.net .

The problem you are facing is that you want your implementations to have different function signatures, which means you probably shouldn't use inheritance to solve your problem.

0
source

Source: https://habr.com/ru/post/887984/


All Articles