PHP: "The declaration ... must be compatible with that ..."

I would like to create an interface for objects that are CRUDable (can be saved and deleted). Here is my abstract class:

abstract class AbstractCrudableEntity extends AbstractEntity { abstract public function doSave(); abstract public function doDelete(); } 

My implementation class needs additional parameters for these methods. Here is the signature of the implementing class:

 class Contact extends AbstractCrudableEntity { public function doSave(User $user, \UberClientManager $manager); public function doDelete(User $user, \UberClientManager $manager); } 

I understand that PHP requires that implementation classes have the same parameters for methods as the parent class (there are several questions that answer this question: this , for example). So this is not a problem.

However, I recently met some code in Symfony dedicated to authentication tokens. The UsernamePasswordToken class extends AbstractToken and has a different set of parameters in the __construct() method: AbstractToken::__construct() versus UsernamePasswordToken::__construct() .

My question is how can symfony do this? What is the difference between this and my code?

+4
source share
2 answers

Overriding constructors are a special case :

Unlike other methods, PHP does not generate an error message of the E_STRICT level when __construct() redefined with different parameters than the parent method __construct() .

You cannot do this with other methods.

+8
source

Your child methods must have the same number of parameters as the abstract methods in the abstract parent class.

The constructor in your example is not abstract - the child simply overrides it.

0
source

Source: https://habr.com/ru/post/1443224/


All Articles