在PHP中调用父类构造函数

时间:2014-02-12 20:42:47

标签: php oop constructor laravel

我有一个控制器

use API\Transformer\DataTransformer;
use API\Data\DataRepositoryInterface;

class DataController extends APIController implements APIInterface {

protected $data;

public function __construct(DataRepositoryInterface $data)
{
    $this->data = $data;        
}

APIController

use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;
use League\Fractal\Manager;

class APIController extends Controller
{
protected $statusCode = 200;

public function __construct(Manager $fractal)
{       
    $this->fractal = $fractal;

    // Are we going to try and include embedded data?
    $this->fractal->setRequestedScopes(explode(',', Input::get('embed')));

    $this->fireDebugFilters();
}

APIController __construct()内部没有任何内容被调用,我尝试parent::__construct();但是当我尝试从APIController

调用一个类时,这个错误(请参阅下面的错误)
Argument 1 passed to APIController::__construct() must be an instance of League\Fractal\Manager, none given, called in /srv/app.dev/laravel/app/controllers/DataController.php on line 12 and defined

换句话说,它试图在DataController中实例化APIController构造函数。如何在APIController之前调用DataController构造函数?

1 个答案:

答案 0 :(得分:2)

您的构造函数需要将所有需要的对象传递给父构造器。父构造函数需要一个Manager对象,因此如果要调用它,则必须将其传入。如果DataRepositoryInterface不是Manager,则需要将管理器传递给childs构造函数,或者将对象实例化为传递给父级的必要类。

 class DataController extends APIController implements APIInterface {

       protected $data;

       public function __construct(Manager $fractal,  DataRepositoryInterface $data) {
            parent::__construct($fractal);
            $this->data = $data;        
        }
  }

或者你可以在你的constuctor中实例化一个Manager

     class DataController extends APIController implements APIInterface {

       protected $data;

       public function __construct(DataRepositoryInterface $data) {
            $fractal = new Manager(); //or whatever gets an instance of a manager
            parent::__construct($fractal);
            $this->data = $data;        
        }
  }