为什么构造函数会在 codeigniter 3 中产生问题?

Why construct function creates issue in codeigniter 3?

我是 codeigniter 3.x 的新手,我在 codeigniter 3.x 中编写

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        echo "ya";
    }
}

它显示错误

404 Page Not Found

The page you requested was not found.

当我写

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        echo "ya";
    }
    public function index() {
        echo "aya";exit;
    }
}

它工作正常并显示输出为 {yaaya}。 谁能告诉我你是这个吗?

发生这种情况是因为 CI 正在寻找 index() 而您还没有提供要执行的操作。对于第一种情况,它不存在,因此引发了错误。但在第二种情况下,它就在那里,所以它起作用了。你不能明确地调用 __construct()

它寻找 controller/action 的默认 url 模式。如果未提供 action,它将在该控制器中查找 index()

因此,当它获得 index() 时,它会实例化控制器 class 并调用 __construct()

这背后的原因是当您 运行 url

http://ip/cifolder/index.php/controller

默认情况下,它会查看此控制器的 index()

如果你用url喜欢

http://ip/cifolder/index.php/controller/function

它将查看您控制器的那个功能

如果你没有在你的控制器中编写任何函数 __construct

function __construct() {
        parent::__construct();
    }

这意味着没有 index() 函数它会告诉你 400 error