18

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 )

1
  • 1
    I tested it and it works fine (after adding a semicolon after the echo) on PHP 5.3.1. Commented Jul 7, 2010 at 10:16

2 Answers 2

28

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Pekka, you're right. I added $GLOBALS['from'] = 'value' outside the function, and the value was found inside myfunc(). I didn't realize this page was generated by CodeIgniter's $this->load->view() function. Thanks!
13 years later ... I've just used IIFE in a legacy code base exactly to isolate globals and it did not even occur to me that I actually needed global scope for globals to work as expected, lol.
17

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.

2 Comments

+1 I've never realized I can say "I've being doing dependency injection since 2002" :)
Thanks, I'll be using Dependency Injection instead :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.