本文介绍了在PHP中调用父类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器

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

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

换句话说,它正在尝试在DataController中实例化APIController构造函数.我如何才能在DataController之前调用APIController构造函数?

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?

推荐答案

您的构造函数需要将所有需要的对象传递给父构造函数.父构造函数需要一个Manager对象,因此如果要调用它,则必须将其传递.如果DataRepositoryInterface不是Manager,则需要将Manager传递给子级构造函数,或实例化一个对象,并将其传递给父级.

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

或者您可以在构造函数中实例化一个Manager

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

这篇关于在PHP中调用父类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:31