Php 实现接口问题
我在构造函数中有一个类型提示,但由于某种原因,我得到了Php 实现接口问题,php,oop,interface,Php,Oop,Interface,我在构造函数中有一个类型提示,但由于某种原因,我得到了 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 { pub
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时,处理程序类的实例将通过日志构造函数传递 您必须添加
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());
谢谢这就成功了。这个问题还有别的解决办法吗?@MZON我真的不这么认为,但我也在这里学习,并愿意接受各种想法:)。如果它说“TestInterface未定义”,而不是将其当前描述为“参数1必须是不存在的类/接口的实例”,那么问题就会更清楚