You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter中getMethod方法已弃用?求原因及修复方案

解决CodeIgniter中Request::getMethod()弃用问题

替代方案

针对getMethod()方法弃用的问题,有两种可行的解决方式:

方式1:直接使用请求类型判断方法(推荐)

CodeIgniter提供了更直观的is()方法来判断请求类型,无需手动比较方法名,彻底规避大小写和弃用问题:

public function insert()
{ 
    if ($this->request->is('post')) { // 不区分大小写,传入'POST'也可正常判断
        $validation = \Config\Services::validation();

        $rules = [
            "txtSN" => [
                "label" => "Student Number",
                "rules" => "required"
            ],
            "txtFN" => [
                "label" => "First Name",
                "rules" => "required|min_length[3]|max_length[20]"
            ],
            "txtMN" => [
                "label" => "Middle Name",
                "rules" => "required|min_length[3]|max_length[20]"
            ],
            "txtLN" => [
                "label" => "Last Name",
                "rules" => "required|min_length[3]|max_length[20]"
            ],
            "cbSex" => [
                "label" => "Sex",
                "rules" => "required"
            ],
            "txtDOB" => [
                "label" => "Date of Birth",
                "rules" => "required"
            ],
        ];
    }
}

方式2:手动处理方法名大小写(需严格匹配时用)

按照PSR-7规范,新版本getMethod()默认返回大写方法名(如'POST'、'GET'),如果确实需要获取方法名并做比较,可直接使用默认返回值:

public function insert()
{ 
    if ($this->request->getMethod() == 'POST') {
        $validation = \Config\Services::validation();

        $rules = [
            "txtSN" => [
                "label" => "Student Number",
                "rules" => "required"
            ],
            "txtFN" => [
                "label" => "First Name",
                "rules" => "required|min_length[3]|max_length[20]"
            ],
            "txtMN" => [
                "label" => "Middle Name",
                "rules" => "required|min_length[3]|max_length[20]"
            ],
            "txtLN" => [
                "label" => "Last Name",
                "rules" => "required|min_length[3]|max_length[20]"
            ],
            "cbSex" => [
                "label" => "Sex",
                "rules" => "required"
            ],
            "txtDOB" => [
                "label" => "Date of Birth",
                "rules" => "required"
            ],
        ];
    }
}

注:若你的CodeIgniter版本中getMethod()默认返回小写,只需将比较字符串改为'post',或用strtoupper($this->request->getMethod())转换后再比较。

内容的提问来源于stack exchange,提问作者Zekken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 02:55:26