P
P
Peppa Pig2019-11-25 14:52:37
PHP
Peppa Pig, 2019-11-25 14:52:37

How does polymorphism work in php through abstract classes and abstract methods?

There is a set of doctrine entities and there is a code that should do something with these entities.
Because there will be a lot of entities and ways to use entities, then I want to designate basic methods in abstract classes.

<?php
namespace App\Entity;

abstract class AbstractEntity;
{
    //...
}

<?php
namespace App\AnotherName;

use App\Entity\AbstractEntity;

abstract class AbstractService
{
    abstract public function create(AbstractEntity $entity);
}

<?php
namespace App\Entity;

class AnotherEntity extend AbstractEntity;
{
    //...
}

The storm began to swear at the following code - the method declaration must match what is in the abstract class.
<?php
namespace App\Service\AnotherName;

use App\Entity\AnotherEntity;

class FooService extend AbstractService
{
    public function create(AnotherEntity $anotherEntity) {
        //...
    }
}

But on such code, it does not swear:
<?php
namespace App\Service\AnotherName;

use App\Entity\AbstractEntity;

class FooService extend AbstractService
{
    public function create(AbstractEntity $anotherEntity) {
        //...
    }
}

And since while phpstorm understands more than I do in terms of php oop, the question arose -
I understand correctly that in order for the create method in service classes inherited from AbstractService to work with any entities inherited from AbstractEntity, you need to leave at the input of the create method of child classes AbstractService parameter type AbstractEntity?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shamanov, 2019-11-25
@SilenceOfWinter

through interfaces: `function setFoo(FooInterface $instance)`, the interface describes methods, abstract classes - the basic implementation of these methods, for example, the implementation of the template adapter on the example of the database: DBMS adapter interface, abstract adapter for mysql implementing interface, class extending mysql abstract adapter php based mysql extension + class extending abstract mysql adapter based on php mysql extension i

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question