Run
Run

Reputation: 57176

Declaration of ... should be compatible with ... - overwrite parent method completely?

I get this error Strict standards: Declaration of Boo::sayHello() should be compatible with Foo::sayHello($param = false) in C:\...

Because I don't set $param = false or true in the extended child class.

class Foo
{
    var $message = 'Hello Foo';

    public function sayHello($param = false)
    {
        return $this->message;
    }
}

class Boo extends Foo
{
    public function sayHello($param)
    {
        return 'Hello Boo';
    }

    public function sayWorld($b)
    {
        return 'Hello World';
    }
}

$boo = new Boo;
var_dump($boo->sayHello('a'));
var_dump($boo->sayWorld('b'));

Is it possible to overwrite completely or redefine the method in the parent class?

By the way, is it a bad practice by doing so?

Upvotes: 0

Views: 671

Answers (1)

Mitch Satchwell
Mitch Satchwell

Reputation: 4830

The reason for the error is that the number of parameters on Boo::sayHello() does not match the parent Foo::sayHello(), by having a default of $param=false on Foo::sayHello() this function can be called with no parameters where as the child class function Boo::sayHello() requires a parameter.

Consider the following function:

function baz (Foo $f) { $f->sayHello(); }

The compiler only checks the correctness of this function call against Foo::sayHello() as any objects of sub-type Foo should have the same method signature for sayHello().

If you passed an object of Boo to the above function this would not work as expected due to the difference in method signatures/required parameters.

You should be able to pass child class objects in place of parent objects - by redefining parent functions with different signatures you are going against this and may result in runtime errors.

Upvotes: 1

Related Questions