• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
make $CI (superobject) global?

i have auto-loaded models and libraries, but before i can use them in my models and library classes i have to type like this:

$CI =& get_instance();

and that's annoying to have to have the first line all the time. so i thought i could have that line in a pre_controller hook.

however, i have to make $CI global for it to work (or that variable will only live in the hook method)

i tried this in the pre_controller hook:

public function set() {
      global $CI;
      $CI =& get_instance();

but it didnt work. how could i make $CI global through the whole application?


I know you say you don't want to call it every time but I would personally say the use of globals is bad practice. It can mean the code gets confusing later on and hard to read since you don't quite know what could be setting the value of this global variable at any point.

Does one extra line really bother you that much?

then why is there an auto-loading function? you could just use $this->load every time right?

it's also how i learn to do things, what i CAN do. and will that be good or bad for the application/coding?

just wonder if it's possible to make it globally? seems hard when "global" doesn't work.

The autoloading function isn't global, its only loads things inside the main CodeIgniter core object. Use of the autoloader is perfectly correct.

But in answer you your question the following happens if you try to do what you want (in PHP4). Are you using PHP4 because it may not be allowed if so.
function test_global_ref() {
    global $obj;
    $obj = &new;stdclass;

function test_global_noref() {
    global $obj;
    $obj = new stdclass;


// This will output
object(stdClass)(0) {

Just because you CAN do something doesn't mean you SHOULD. Since PHP is not a fully OOP language and since PHP is procedural you can use them since they will only be around really for a single HTTP request. I will say it can make finding problems in the code more difficult. You will most likely be fine with using it in this case, I'm just saying it's not the best practice to get into unless you realllly can't avoid it.

weird...it worked in a test.php page but not in a CI controller. maybe CI is running a controller in an isolated environment?

thanks for your thoughts about proper coding style though.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.