0

I have a Content Management System, where slug-based constants for each logged-in user's appropriate directories are defined for one or all controllers within the model. I happen to stumble upon this find by experimenting with redefining constants per logged-in user.

I did not think redefining constants was possible, but I think I am not understanding how Codeigniter or PHP is able to redefine constants in this fashion. I do not receive any PHP error stating that it was unable to redefine constants, so has me to believe that the model or controller instance is unset for each controller?

Controller:

class Content extends CI_Controller {
    function __construct()
    {
        parent::__construct();
        $this->load->model('main_model');

        ...
            get slug from logged_in user
        ...

        $this->main->set_slug_based_constants($slug)
    }
}

One main model (I know it's bad to do this):

class Main_model extends CI_Model{

    public function set_slug_based_constants($slug)
    {
        define('CLOUDFRONT_DIRECTORY', $slug.'_cloudfront_directory');
    }
}

From Codeigniter Docs: Dynamic Instantiation. In CodeIgniter, components are loaded and routines executed only when requested, rather than globally.

So I would like to believe that my assumption is correct in this case based on the Codeigniter Docs.

4

1 回答 1

1

与其说是“未设置”,不如说是“尚未定义”。每个浏览器对 URL(控制器)的请求都是服务器中的一个唯一过程。所以这个常量没有被重新定义,而是为每个 URL 请求重新实例化。

如果您尝试$this->main_model->set_slug_based_constants($slug);第二次运行,您收到一条 PHP 错误消息,指出已定义常量 CLOUDFRONT_DIRECTORY。

试试这个版本的控制器看看错误。

class Content extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('main_model');
        $this->main_model->set_slug_based_constants("Dave");
    }

    function index()
    {
        echo "The constant's value is <strong>".CLOUDFRONT_DIRECTORY."</strong><br>";
        $this->main_model->set_slug_based_constants("jruser");
        echo "The constant's value is  <strong>".CLOUDFRONT_DIRECTORY."</strong><br>";;
    }

}

它将产生类似这样的输出。

常量的值为Dave_cloudfront_directory

遇到 PHP 错误

严重性:通知

消息:已定义常量 CLOUDFRONT_DIRECTORY

文件名:models/Main_model.php

行号:13

常量的值为Dave_cloudfront_directory

于 2016-08-19T13:58:13.560 回答