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?
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.
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.
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With