我在构造函数中有一个类型提示,但由于某种原因我得到了
Catchable fatal error: Argument 1 passed to Log::__construct() must be an instance of TestInterface, instance of Log\Handler given, called in
测试接口(interface).php
namespace Log;
interface TestInterface
{
public function log();
}
处理程序.php
namespace Log;
require_once 'TestInterface.php';
use Log\TestInterface;
class Handler implements TestInterface
{
public function log()
{
//some logic goes here
}
}
日志.php
require_once 'Handler.php';
use Log\Handler;
class Log
{
public function __construct(TestInterface $handler)
{
$handler->log('test');
}
}
$obj = new Log(new Handler());
那么为什么我会收到此错误?我认为当我实现 TestInterface 时,Handler 类的实例将通过 Log 构造函数传递。
最佳答案
您必须将 use Log\TestInterface;
添加到 Log.php 的顶部,因为 TestInterface 在全局命名空间中未定义。您返回的根本不是有用的错误消息,但这应该可以做到:
require_once 'Handler.php';
use Log\Handler;
use Log\TestInterface;
class Log
{
public function __construct(TestInterface $handler)
{
$handler->log('test');
}
}
$obj = new Log(new Handler());
关于php - 实现接口(interface)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25310269/