Is it possible to make a method on a child class of an abstract parent required, yet still allow the method signature to be optional or different from the defined parent method signature?
abstract class Parent
{
abstract public function foo();
}
class Child extends Parent
{
public function foo(Request $request) {
// do something with request
}
}
I need to be able to enforce that specific methods exist on the child, yet allow the user to pass in whatever they want to that class.
It seems you can't do this with either abstract methods or interfaces, how does one go about getting this done?
You can't use a different number of parameters, or type hinting of a different type, with an abstract class. You'd have to check the parameter to verify it is the object type you expected.
If you're going to pass multiple arguments to some versions of foo()
then it gets more messy. You would have to use something like foo(...$variable)
and then check each array position for what that version of foo()
expects.
abstract class Parent
{
abstract public function foo($unused);
}
class Child extends Parent
{
public function foo($request) {
// check type of $request
if ('object' != gettype($request) || 'Request' != get_class($request)) {
// throw your exception here
}
// do something with request
}
}