Welcome Guest, Not a member yet? Register   Sign In
make $CI (superobject) global?
#1

[eluser]ajsie[/eluser]
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();
$CI->classname->method();

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:

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

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

thanks!
#2

[eluser]adamp1[/eluser]
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?
#3

[eluser]ajsie[/eluser]
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.
#4

[eluser]adamp1[/eluser]
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.
Code:
function test_global_ref() {
    global $obj;
    $obj = &new;stdclass;
}

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

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);

// This will output
NULL
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.
#5

[eluser]ajsie[/eluser]
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.




Theme © iAndrew 2016 - Forum software by © MyBB