'codeigniter 4 return error: Call to a member function getVar() on null only in the construct
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.
Solution 1:[1]
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
}
}
Solution 2:[2]
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
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marcogmonteiro |
| Solution 2 | roev |
