簡體   English   中英

從子類構造函數中訪問父類方法

[英]Access parent class methods from within child class constructor

我正在使用Laravel 5.3。 在擴展請求類的表單請求中,我嘗試從父類訪問方法,但是它引發了錯誤,我似乎看不出為什么。 我的表單請求構造函數如下所示。 我在這里想念什么嗎?

當我將其放在其他方法中時,調用將起作用,而不僅僅是在理想情況下從構造函數中調用。

在下面訪問父級將觸發“致命錯誤:在vendor \\ laravel \\ framework \\ src \\ Illuminate \\ Http \\ Request.php:601中對null成員函數get()的調用”

    protected $test= [];

    public function __construct(myRepositoryInterface $myRepository) {

        $this->myRepository= $myRepository;
        if( parent::has('someName') ){
           $this->test= $myRepository->someMethod(parent::input('someName'));
       }
   }

有一些問題。

首先,Laravel的Form Request類是Symfony的Request類的子類。 如果您看一下該類,則它具有以下構造函數:

public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
    $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
}

您創建了自己的構造函數,並更改了Request類的行為,從本質上破壞了它。 您不接受超類所需的任何參數。

Call to a member function get() on nullCall to a member function get() on null提供了一個線索。 這是調用get()的函數:

protected function retrieveItem($source, $key, $default)
{
    if (is_null($key)) {
        return $this->$source->all();
    }

    return $this->$source->get($key, $default);
}

您的$source為空。 $source可以類似於headers屬性,由於您使用了新的構造函數,因此該屬性為null。 該錯誤與父類的has方法無關,與構造函數無關。

其次,您應該調用$this->has()而不是調用parent::has() $this->has()

最后,我將其從構造函數中刪除。 在其他地方初始化您的存儲庫。 如果出於某種原因確實需要將其放入構造函數中,請嘗試接受所有其他參數,然后再接受存儲庫。 記住要調用parent::__construct(...parameters... )並運行自己的邏輯。

您可能會忘記在子構造函數中調用parent :: __ construct()嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM