Reputation: 786
I have a class like this
class Parent {
public function add($query = "", $queryParams = []) {
if(empty($query)) {
$query = "blablabla";
}
if(empty($params)) {
$params = [blablabla];
}
//... some logic;
//return something;
}
}
and I want to have a Child class like this
class Child extends Parent {
public function add() {
$query = "blablabla";
$params = [blablabla];
return parent::add($query, $params);
}
}
But it always throws me an error saying the child class method must be 'compatible', it means I have to declare the same parameters.
I was thinking of something like declaring a function in the parent like this:
public function __add($query = "", $params = []) {}
and in the child class declare the function like this:
public function add() {
$query = "blabla"; $params = [blabla];
return parent::__add($query, $params);
}
One problem is that I still need to use some Parent class Objects and the method add(), I not always use only Inherited classes object.
Any ideas?
Upvotes: 0
Views: 160
Reputation: 214969
Although you could just ignore "strict" messages, this one is given for a reason: changing signatures of parent methods is a Bad Thing, as it violates the famous "Liskov Substitution Principle": a Child class should always be able to replace its Parent. For example, if you have something like
$p = new Parent();
$p->do_this()
$p->and_that()
$p->add(x,y)
and if you replace the first line with
$p = new Child();
the rest of the code should work as before. Obviously, changing the signature will cause it to break.
Create a new method in the Child, e.g. addWithDefaults()
or similar, and leave the inherited add()
in peace.
Upvotes: 1