Laravel Tinker创建具有构造函数作为接口的新对象

dan*_*l8x 0 php laravel laravel-5 tinker

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

class MyClass{
 public function __construct(ApiInterface $APIloader)
    {
        $this->APIloader = $APIloader;
    }
}
Run Code Online (Sandbox Code Playgroud)

ApiInterface.php

interface ApiInterface {
    ..
    ..
}
Run Code Online (Sandbox Code Playgroud)

我想在修补程序中测试我的类,所以我所做的是:

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

我得到的错误是:

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

修补匠不允许我todo,我觉得修补匠不认识一个接口作为一个类

任何的想法 ?

谢谢

Akn*_*sis 5

您无法创建接口的实例.

如果你想测试你的代码,那就创建一个虚拟类并使用它.

class TestApi implements ApiInterface {}

$a = new App\MyClass(new App\TestApi);
Run Code Online (Sandbox Code Playgroud)

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