【问题标题】:Implementing interface issue实现接口问题
【发布时间】:2014-08-14 14:11:49
【问题描述】:

我在构造函数中有一个类型提示,但由于某种原因我得到了

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();
    }

处理程序.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 构造函数传递。

【问题讨论】:

    标签: php oop interface


    【解决方案1】:

    您必须将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 我真的不这么认为,但我也在这里学习,并对想法持开放态度:)。如果它说“未定义测试接口”而不是当前描述为“参数 1 必须是不存在的类/接口的实例”,问题会更清楚
    猜你喜欢
    • 2011-03-19
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    相关资源
    最近更新 更多