Calling parent class constructor in PHP

对着背影说爱祢 提交于 2019-12-11 12:12:15

问题


I have a controller

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

class DataController extends APIController implements APIInterface {

protected $data;

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

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

Nothing inside the APIController __construct()is being called, I have tried parent::__construct(); but this errors (see error below) when I try and call a class from the 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

In other words it is trying to instantiate the APIController constructor in the DataController. How can I get it to call the APIController constructor before the DataController?


回答1:


Your constructor needs pass all needed objects to the parent constuctor. The parent constructor needs a Manager object, so you must pass it in if you want to call it. If DataRepositoryInterface is not a Manager, you'll need to pass a manager into your childs constructor or instantiate an object the necessary class to pass to the parent.

 class DataController extends APIController implements APIInterface {

       protected $data;

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

Or you could instantiate a Manager inside your constuctor

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


来源:https://stackoverflow.com/questions/21739155/calling-parent-class-constructor-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!