Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding parameters to overridden method E_STRICT observation

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?

like image 640
jbarreiros Avatar asked Jul 14 '11 21:07

jbarreiros


People also ask

Can an overridden method have different parameters?

No, while overriding a method of the super class we need to make sure that both methods have same name, same parameters and, same return type else they both will be treated as different methods.

What happens when you override a method?

Instance Methods The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides.

Can overridden method be more restrictive?

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.


1 Answers

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.

like image 73
Dan King Avatar answered Oct 16 '22 00:10

Dan King