Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must child method has same parameters as parent method?

Tags:

php

overriding

I have this code:

abstract class Base{

   public function delete(){
     // Something like this (id is setted in constructor)
     $this->db->delete($this->id);
   }

}

Then i Have another class which extends Base, for instance:

class Subtitles extends Base{

    public function delete($parameter){
         parent::delete();
         // Do some more deleting in transaction using $parameter
    }

}

which also happens to have method delete.

Here comes the problem:

When i call

$subtitles->delete($parameter)

I get the:

Strict error - Declaration of Subtitles::delete() should be compatible with Base::delete() 

So my question is, why i can't have the method of descendant with different parameters?

Thank you for explaining.

like image 813
Martin Svoboda Avatar asked Oct 24 '25 18:10

Martin Svoboda


2 Answers

This is because PHP does method overriding not method overloading. So method signatures must match exactly.

As a work arround for your issue you can restructure delete on your base class to

public function delete($id = null){
  // Something like this (id is setted in constructor)
  if ($id === null) $id = $this->id;
  $this->db->delete($id);
}

Then change your subclasses method signature to match.

like image 98
Orangepill Avatar answered Oct 27 '25 08:10

Orangepill


To override the function in the base class, a method must have the identical "Signature" to the one it is displacing.

A signature consists of the name, the parameters (and parameter order), and the return type.

This is the essence of polymorphism, and is where object-oriented programming gains much of its power. If you don't need to override the parent's methods, give your new method a different name.

like image 20
Curt Avatar answered Oct 27 '25 10:10

Curt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!