Home > front end >  Pass in a interface type as a function parameter throws "Delaration must match ..."
Pass in a interface type as a function parameter throws "Delaration must match ..."

Time:07-30

I want to be able to pass in an object that implements IEntity interface but I'm facing a

PHP Fatal error:  Declaration of ShirtOrderRepository::find(ShirtOrder $shirtOrder) must be compatible with RepositoryInterface::find(IEntity $entity) in /Users/okkamiadmin
/projects/Befeni/index.php on line 52

error how can I achieve this as I'm not sure if I'm doing it the right way?

<?php

interface IEntity {
    public function getTableName();
}

class ShirtOrder implements IEntity
{
    public $id;
    public $customerId;
    public $fabricId;
    public $collarSize;
    public $chestSize;
    public $waistSize;
    public $wristSize;

    public function getTableName()
    {
        return 'shirt_orders';
    }
}

interface RepositoryInterface
{
    public function find(IEntity $entity);
    public function save(IEntity $entity);
    public function remove(IEntity $entity);
}

interface DatabaseInterface {

    public function find(IEntity $entity);
    public function save(IEntity $entity);
    public function remove(IEntity $entity);

}

class ShirtOrderRepository implements RepositoryInterface {
    protected $db;

    public function __construct(DatabaseInterface $db) {
        $this->db = $db;
    }

    public function find(ShirtOrder $shirtOrder)
    {
        $this->db->find($shirtOrder);
    }

    public function save(ShirtOrder $shirtOrder)
    {
        $this->db->save($shirtOrder);
    }

    public function remove(ShirtOrder $shirtOrder)
    {
        $this->db->remove($shirtOrder);
    }
}

CodePudding user response:

You need to pass type of IEntity instead of ShirtOrder at ShirtOrderRepository class like so:

public function find(IEntity $shirtOrder){
  $this->db->find($shirtOrder);
}

Also you need to do this for the rest of the methods since RepositoryInterface expects type of IEntity passed in its methods parameters.

  • Related