【问题标题】:Laravel Tinker creating new object that have constructer as an interfaceLaravel Tinker 创建具有构造函数作为接口的新对象
【发布时间】:2018-04-09 09:02:15
【问题描述】:

我正在尝试使用 Laravel Tinker 创建一个具有构造函数作为接口的新对象。 MyClass.php

class MyClass{
 public function __construct(ApiInterface $APIloader)
    {
        $this->APIloader = $APIloader;
    }
}

ApiInterface.php

interface ApiInterface {
    ..
    ..
}

我想在 tinker 中测试我的课程,所以我所做的是:

  1. php artisan tinker
  2. >> $a = new App\MyClass(new App\ApiInterface);

我得到的错误是:

PHP 致命错误:在第 1 行的 eval() 代码中找不到类“App\ApiInterface”

修补匠不允许我做我觉得修补匠无法将接口识别为类的事情

有什么想法吗?

谢谢

【问题讨论】:

    标签: php laravel laravel-5 tinker


    【解决方案1】:

    您不能创建接口的实例。

    如果您想测试您的代码,请创建一个虚拟类并使用它。

    class TestApi implements ApiInterface {}
    
    $a = new App\MyClass(new App\TestApi);
    

    http://php.net/manual/en/language.oop5.interfaces.php

    比虚拟类更好的选择是使用模拟对象。他们在程序上完成同样的事情。

    https://laravel.com/docs/5.5/mocking

    https://phpunit.de/manual/current/en/test-doubles.html

    【讨论】:

    • @trinhdh 如果这个答案对你有帮助,请考虑接受它
    • 我应该把接口作为这样的参数:__construct(ApiInterface $APIloader)
    • @ljubadr 我会的。 Stackoverflow 暂时不允许我这样做。
    • @trinhdh 将接口作为构造函数参数是完全有效的。
    猜你喜欢
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 2023-03-17
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多