kid_plama
kid_plama

Reputation: 249

Why class that implements a interface is not an instance of that interface?

I want to do dependency injection like this

<?php
    class UserModel
    {
        public function __construct(DatabaseInterface $db)
        {
            $this->db = $db;
        }
    }

So I have created the Database class and an interface for it

<?php
    interface DatabaseInterface {}

    class PdoConnection implements DatabaseInterface
    {
        ...

But when I try to make instance of UserModel passing an instance of PdoConnection I get an error

$user = new UserModel(new \Manager\Database\PdoConnection);

__construct() must be an instance of DatabaseInterface, instance of Manager\Database\PdoConnection given

I am not sure why since the PdoConnection implements DatabaseInterface so I believe UserModel should just accept it?

Debugging below

$class = new \Manager\Database\PdoConnection();
if ($class instanceof DatabaseInterface) {
    echo "variable class is a instance of DatabaseInterface";
} else {
    echo "variable class is not a instance of DatabaseInterface";
}

var_dump(class_implements($class));

Results

variable class is not a instance of DatabaseInterface

array(1) {
  'Manager\Database\DatabaseInterface' =>
  string(34) "Manager\Database\DatabaseInterface"
}

Upvotes: 1

Views: 169

Answers (1)

Adder
Adder

Reputation: 5868

You need to write Manager\Database\DatabaseInterface everywhere instead of simply DatabaseInterface.

Upvotes: 1

Related Questions