类不返回接口实例PHP


Class Not Returning Interface Instance PHP

我在一个实现接口的类上遇到了一个奇怪的错误。

错误:

可捕获的致命错误:参数1传递给MyApp''Library''Cache::__construct((必须是的实例MyApp''Contacts''CacheInterface,MyApp''Driver''Cache''File的实例给定

文件类:

namespace MyApp'Driver'Cache;
use MyApp'Library'Config;
use MyApp'Contracts'CacheInterface;
class File implements CacheInterface {
    private $expire;
    public function __construct($expire, Config $config) {
        $this->expire = $expire;
        $this->config = $config;
        ... more code
    }
}

缓存类:

namespace MyApp'Library;
use MyApp'Contacts'CacheInterface;
final class Cache {
    private $cache;
    public function __construct(CacheInterface $cache) {
        $this->cache = $cache;
    }
    ... more methods
}

接口:

namespace MyApp'Contracts;
interface CacheInterface {
    public function get($key);
    public function set($key, $value);
    public function delete($key);
    public function flush_cache();
}

在Pimple容器中作为服务实现,如下所示:

$this->data['cache'] = function ($data) {
    switch ($data['config_cache_type_id']):
        case 'apc':
            $driver = new Apc($data['cache.time'], $data['config']);
            break;
        case 'mem':
            $driver = new Mem($data['cache.time'], $data['config']);
            $driver->connect();
            break;
        case 'file':
        default:
            $driver = new File($data['cache.time'], $data['config']);
            break;
    endswitch;
    return new Cache($driver);
};

当然,这4个Driver和Cache类包含在容器类之前的use关键字中。

我看不出我错过了什么——我已经用完全相同的程序签订了其他几份合同。任何想法都将不胜感激。

在您的File.class中,您可以尝试替换:吗

use MyApp'Contracts'CacheInterface;

use MyApp'Contacts'CacheInterface;

对于您的界面,请使用:

namespace MyApp'Contacts;