codeigniter 代码点火器4返回错误:仅在构造中对空值调用成员函数getVar()

b4wnujal  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(125)

在我的Codeigniter 4项目中,我收到了一条错误消息:Call to a member function getVar() on null。它只发生在构造中:命名空间应用\控制器;

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
}

有什么建议吗?谢谢。

tcbh2hod

tcbh2hod1#

您确实不应该在控制器中使用__construct。
相反,您应该使用与baseController相同的结构和iniController,这样您就可以访问请求响应和记录器。

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
    }
}

如果你真的想使用__construct,那么你必须按照这里所说的去做,但是你可以使用服务助手,这样它的方式会更干净,如下所示:

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
   }
}
2nc8po8w

2nc8po8w2#

解决方案:

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
    }
}

相关问题