Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP global variable is undefined inside a function even if global keyword is used

Yes I know global variables is a bad practice, but ease up on that rule for this one :P

My code:

include('something.php'); //where $from is declared

function myfunc() {
    global $from;
    echo "from(myfunc)=$from<br />";
    ...
}

echo "from=$from<br />";
myfunc();

The result is:

from=2010-05-01
from(myfunc)=

What's going on? :(

EDIT: If it helps, all the code above is inside a view file in CodeIgniter ( and yes, I know functions are not supposed to be inside views :P )

like image 870
Obay Avatar asked Jul 07 '10 10:07

Obay


2 Answers

I'll bet a beer you are not inside the global scope with this snippet. Are you calling this from within a function?

In that case, the $from you define in something.php is not global, while the one you reference in the function is.

It will probably work if you add a global $from; inside something.php before you define $from.

Needless to say, it's not a nice practice either way, and you should follow Gordon's advice.

like image 84
Pekka Avatar answered Oct 13 '22 18:10

Pekka


Do yourself a favor and use Dependency Injection.

function myfunc($from) {
    return "from(myfunc)=$from<br />";
}
$from = '2010-05-01';
echo myfunc($from);

Doing so will make your code more maintainable, less coupled and more easily unit-testable because it is isolated from the global scope. Plus, when you do it people think you are cool.

like image 35
Gordon Avatar answered Oct 13 '22 19:10

Gordon