Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PHP child classes alter parameters of overridden methods?

Tags:

oop

php

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?

like image 542
DatsunBing Avatar asked Jul 26 '12 21:07

DatsunBing


People also ask

Can you override methods in PHP?

Introduction to the PHP overriding method Method overriding allows a child class to provide a specific implementation of a method already provided by its parent class. To override a method, you redefine that method in the child class with the same name, parameters, and return type.

What happens if you attempt to access a private method of a parent class from its child class in PHP?

... private methods are visible only for the class that defines them and the child class does not see the parent's private methods. ...

How to call parent class function in child class in PHP?

In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

How can you prevent a class from overriding in PHP?

PHP - The final Keyword The final keyword can be used to prevent class inheritance or to prevent method overriding.


1 Answers

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?

like image 107
jerome Avatar answered Oct 08 '22 06:10

jerome