How to add a class type to an abstract method parameter?

I have an abstract class using this method:

abstract class X { abstract public function method( $param ); } 

In the implementation, I do:

 class Y extends X { public function method( ClassName1 $param ) { ... } } class W extends X { public function method( ClassName2 $param ) { ... } } 

I need to put ClassName1 and ClassName2 in both methods, but I get this error:

The declaration of Y::method() must be compatible with X::method($param) in ...

What do I need to declare an abstract method in class X to solve the problem? Perhaps the real question arises: what should be the class name in X::method( _____ $param ) to solve the problem?

Thanks.

+5
source share
3 answers

You can create an interface. ClassName1 and ClassName2 implement this interface. Now you can use your interface as a hint type in the method parameter. Based on your polymorphism tag, you can know how to use interfaces, what they are and what are the benefits. This approach is called Design by Contract and is considered best practice.

+6
source

I do not think that you will be able to do this because you are a type, hinting at two different classes. When you use abstract or interface , it is basically a promise to implement a method in the same way as it was previously defined. Your addition of type hints makes them clearly incompatible.

The best I can offer is to do a check inside the method itself

 class Y extends X { public function method( $param ) { if(get_class($param) != 'ClassName1') throw new Exception('Expected class ClassName1'); } } 
+2
source

I think this is the only way to go?

 class A {} class B extends A {} class C extends A {} abstract class X { public abstract function method( A $param ); } class Y { public function method(B $param ) {} } class Z { public function method(C $param ) {} } $y = new Y(); $z = new Z(); ?> 
+1
source

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


All Articles