I have an abstract class with 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 the ClassName1
and the ClassName2
in both methods, but I get this error:
Declaration of Y::method()
must be compatible with X::method($param)
in ...
What I need to declare the abstract method in class X to solve the problem?
The real question maybe: What be the class name in X::method( _____ $param )
to solve the problem?
Thanks.
The answer to this is: you cannot do it. This is a mathematical fact and has nothing to do with the programming language involved.
Yes, we can provide parameters to abstract method but it is must to provide same type of parameters to the implemented methods we wrote in the derived classes.
Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .
We cannot create objects of an abstract class. To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass. A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.
You can create an interface. ClassName1
and ClassName2
implement that interface. Now you can use your interface as a type-hint in your method parameter. Based on your tag polymorphism
, you may know how to use interfaces, what they are and what the benefits are. This approach is called Design by contract and is considered best practice.
I don't think you're going to get away with doing this because you're type hinting two different classes. When you use an abstract
or interface
, it's basically a promise to implement a method in the same way the it's been previously defined. Your adding of the type hint makes them decidedly incompatible.
The best thing I can suggest is to do the check inside the method itself
class Y extends X {
public function method( $param )
{
if(get_class($param) != 'ClassName1') throw new Exception('Expected class ClassName1');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With