6

I can override a PHP method in a child class and change the parameters in the signature, as shown below.

class theParent {
  function myMethod($param1) {
    // code here
  }
}

class theChild extends theParent {
  function myMethod($param1, $param2) {
    // code here
  }
}

I tested this and it works fine and does not raise any errors. My question is, is this bad form? Or a basic tenet of OOP?

If the parent method is declared abstract the child signatures can not deviate. Presumably this is the mechanism to use if you need to enforce that aspect of the interface?

DatsunBing
  • 8,684
  • 17
  • 87
  • 172
  • 1
    That child class isn't a child of the first class. Not to mention that it's invalid syntax... – nickb Jul 26 '12 at 21:49
  • It's called **override**. If you want to prevent a child class from overriding a method use the [final](http://php.net/manual/en/language.oop5.final.php) keyword. – Fabio Mora Jul 26 '12 at 22:33

3 Answers3

3

You will throw a strict standards error message by not matching the parent class's number of parameters for that method.

More info here...

Why is overriding method parameters a violation of strict standards in PHP?

Community
  • 1
  • 1
jerome
  • 51
  • 3
0

What you have done is called overriding and it is fine nothing bad but if you want to make child classes stick to the signature of parent better you use the interfaces as below You should just give just signatures and the child classes mut implement them as they are declared.

 interface theParent {
      function myMethod($param1) ;
    }

    class theChild extends theParent {
      function myMethod($param1) {
        // code here
      }
    }

Hope it helps :)

Rupesh Patel
  • 3,015
  • 5
  • 28
  • 49
-1

As long as

class theChild extends theParent {
}

It's a good example of OOP.

Matt
  • 6,993
  • 4
  • 29
  • 50