我在构造函数中有一个类型提示但由于某种原因我得到了
Catchable fatal error: Argument 1 passed to Log::__construct() must be an instance of TestInterface, instance of Log\Handler given, called in
TestInterface.php
namespace Log;
interface TestInterface
{
public function log();
}
Handler.php
namespace Log;
require_once 'TestInterface.php';
use Log\TestInterface;
class Handler implements TestInterface
{
public function log()
{
//some logic goes here
}
}
Log.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构造函数传递。
答案 0 :(得分:2)
您必须将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());