adding parameters to overridden method E_STRICT ob

2019-02-21 16:48发布

问题:

It appears (PHP 5.3) that if you are overriding a class method, it is okay to you can add additional parameters, as long as they have default values.

For example, consider the class:

class test1 {
  public function stuff() {
    echo "Hi";
  }
}

The following class extends "test1" and will produce an E_STRICT warning.

class test2 extends test1 {
  public function stuff($name) {
    echo "Hi $name";
  }
}

But, the following does not produce an E_STRICT warning.

class test3 extends test1 {
  public function stuff($name = "") {
    echo "Hi $name";
  }
}

While class "test3" doesn't produce an E_STRICT warning, I have been under the impression that PHP does not allow method signatures to be overloaded overridden. So, I have to ask. Is my observation a bug/flaw or actually correct intended behavior?

Further, if a default argument parameter is okay, why is a non-default argument parameter not okay?

回答1:

If you add a non-defaulted parameter to an overridden method, the subclass no longer satisfies the contract defined by the superclass. You cannot correctly call test2->stuff(), because this method now expects a parameter - but the superclass says you should be able to call it without one. Hence the E_STRICT warning.

If you add a defaulted parameter though, you can still call test3->stuff() (from your example) - as the superclass expects - and so the contract is not broken. In fact, by adding the optional parameter, you have simply extended it.



回答2:

This is not a bug and is acceptable PHP programming practise.

Please note that multiple overrides can cause programmer headaches though and should be avoided where possible.

Alternatively I usually either have a single extended class to override per class or just overload a class method within the actual class itself.