バーテンダーエンジニア

元フレアバーテンダーからエンジニアに転職。未経験からのエンジニア転職経験談・実務で感じたこと・個人開発で学んだ内容・日常話などマイペースに発信していきます。仕事ではphp、Laravel、Vue.js、Angular辺りを触ってます。趣味は筋トレ!!ソムリエの資格も持ってます^^

Call to a member function メソッド名 on nullエラーの解決

はじめに

Laravelでバックエンドを開発中以下のエラーに遭遇しました。

Call to a member function getIndex() on null

最初原因が特定できずに困っていたので、備忘録として残しておきます。

開発環境

Mac OS Catalina 10.15.6
PHP 7.3
Laravel 6.20.2

エラー内容

Call to a member function getIndex() on null

こちらの意味はgetIndexが存在しないオブジェクト(というかnull)に対して実行しようとしているというものです。該当の箇所は以下のように記載していました。

<?php
namespace App\Http\Actions;

use App\Http\Controllers\Controller;
use App\Http\Responder\BookResponder;
use App\Domain\BookDomain;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

final class BookIndexAction extends Controller
{
    protected $domain;
    protected $responder;

    public function __constract(BookDomain $domain, BookResponder $responder)
    {
        $this->domain = $domain;
        $this->responder = $responder;
    }

    /**
     * 書籍一覧画面データを取得
     *
     * @param Request $request
     * @return void
     */
    public function __invoke(Request $request): JsonResponse
    {
        $data = $this->domain->getIndex();
    }
}

こちら$this->domainがすでにNULLになっている模様。
確認するとpublic function __constructにタイポが。。。。単純なミスでした。
急いでVS codeにスペルチェックをいれました!!

marketplace.visualstudio.com