get_instance() in Codeigniter: Why assign it to a variable?

后端 未结 7 1674
清酒与你
清酒与你 2020-12-04 08:42

In Codeigniter, get_instance() is a globally available function that returns the Controller super-object which contains all the currently loaded classes (it ret

7条回答
  •  再見小時候
    2020-12-04 09:13

    Getting the result of get_instance() by reference just makes no sense since PHP5. Sadly this bad habit seems to be deep-rooted, so let's just deal with it.

    For those interested, here's an über fast instance getter:

    function CI()
    {
        static $CI;
        isset($CI) || $CI = CI_Controller::get_instance();
    
        return $CI;
    }
    

    Note that the static variable wouldn't work if it were assigned by reference.

    Also, you are forced not to get by reference the result of this CI(). Extra sugar :-)

    Ah, and obviously you still have the (slight) cost of the function call. You still may want to use a variable instead of calling the function dozens of times.

提交回复
热议问题