【问题标题】:Calling parent class constructor in PHP在 PHP 中调用父类构造函数
【发布时间】:2023-03-15 10:29:01
【问题描述】:

我有一个控制器

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 构造函数。如何让它在DataController 之前调用APIController 构造函数?

【问题讨论】:

  • 没错——它是parent::__construct()
  • 即使将parent::__construct() 添加到DataController,您仍然需要将Manager 对象传递给父构造函数。我从未见过具有不同构造函数签名的父/子类,并不是说不能这样做,但它确实表明设计中存在潜在的危险信号。

标签: php oop constructor laravel


【解决方案1】:

您的构造函数需要将所有需要的对象传递给父构造函数。父构造函数需要一个Manager对象,所以要调用就必须传入。如果 DataRepositoryInterface 不是管理器,则需要将管理器传递给子构造函数或实例化一个对象,该对象是传递给父级的必要类。

 class DataController extends APIController implements APIInterface {

       protected $data;

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

或者你可以在你的构造函数中实例化一个 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;        
        }
  }

【讨论】:

  • 它们实际上属于不同类型(很可能)
  • 您能解释一下为什么将 DataRepositoryInterface 传递给父类会有帮助吗?
  • 啊,是的,一切都说得通。谢谢。
猜你喜欢
  • 2010-12-06
  • 2011-03-06
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
  • 2018-01-31
  • 2021-05-08
  • 2016-12-11
  • 1970-01-01
相关资源
最近更新 更多