Home > Software engineering >  codeigniter 4 return error: Call to a member function getVar() on null only in the construct
codeigniter 4 return error: Call to a member function getVar() on null only in the construct

Time:04-27

in my codeigniter 4 project i got an error massage: Call to a member function getVar() on null. It just happens in the construct: namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Response;

public function __construct() {
    $this->request->getVar('key'); //Not works
}

public function index() {
    $this->request->getVar('key'); //Works
}

Any suggestions? Thanks.

CodePudding user response:

You really shouldn't be using __contruct in your controllers.

Instead you should use the same structure as your baseController with a iniController and with that you will be having access to both request reponse and logger.

use CodeIgniter\RESTful\ResourceController;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Response;

class SomeName extends ResourceController {

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) {
        $this->request->getVar('key'); //Not works
    }

    public function index() {
        $this->request->getVar('key'); //Works
    }
}

If you really want to use the __contruct then you'll have to do as it was said here but you can use the service helper so its way more cleaner like so:

use CodeIgniter\RESTful\ResourceController;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Response;

class SomeName extends ResourceController {
    
   public function __construct() {
       service('request')->getVar('key'); //Now it works
   }
}

CodePudding user response:

The solution:

use CodeIgniter\RESTful\ResourceController;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Response;
use Config\Services;

class SomeName extends ResourceController {
    protected $request;

    public function __construct() {
            $this->request = Services::request();

            $this->request->getVar('key'); //Now it works
    }

    public function index() {
            $this->request->getVar('key'); //Works
    }
}
  • Related