Skip to content
Advertisement

PHP Overriding methods rules

I just read from the book:
“In PHP 5, except for constructors, any derived class must use the same signature when overriding a method”
From the PHP manual in the comments:
“In the overriding, the method names and arguments (arg’s) must be same.
Example:
class P { public function getName(){} }
class C extends P{ public function getName(){} } “

So why I’m able to replace method with other arguments and their quantity? Is this legal or will trigger errors in the future or I’m just missing something?

PHP Version 5.5.11

JavaScript

This will output:

Test: The Cat was born
Status: None
Cat started to play a chess in the backyard
Status: playing chess in the backyard

Advertisement

Answer

The rule is that a method signature must be compatible with the method it overrides. Let’s look at the two methods in your hierarchy:

JavaScript

The changes:

  1. Visibility: protected -> public; increasing the visibility is compatible (the opposite will cause errors).

  2. Arguments: no change (same number of required arguments and maximum number of arguments)

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement