8

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
jbarreiros
  • 1,103
  • 1
  • 10
  • 21
  • i have error_reporting(E_ALL) set and cannot reproduce the E_STRICT erorr. can you post the error that you are seeing? Also, this is not a case of 'overloading', it is 'overwriting'. – helloandre Jul 14 '11 at 21:23
  • @helloandre, E_STRICT not included in E_ALL. To turn on E_STRICT notices, set `error_reporting(E_ALL | E_STRICT);` – OZ_ Jul 14 '11 at 21:30
  • 1
    @helloandre and E_STRICT isn't generated for this case :) – OZ_ Jul 14 '11 at 21:36
  • No, it's not Ok. Read about [Liskov substitution principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle) And PHP allows to do it. – OZ_ Jul 14 '11 at 21:26
  • I am not getting any error belongs to E_STRICT.I am getting outputs. – Vikas Kumar Jul 08 '14 at 17:31

2 Answers2

5

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.

Dan King
  • 3,412
  • 5
  • 24
  • 23
-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.

AO_
  • 2,573
  • 3
  • 30
  • 31