It’s funny. Even after nearly 10 years with the language, there are still little gotchas that sometimes get me. I ran across one today.
Say you have two objects, and the look like this:
It doesn’t work. You get NULL.
Say I were to do something like this:
You also get NULL. And this:
The reason is that the global scope on PHP is just that: global. Any time you’re in a function or method, you’re in a local scope and all local scopes are independent of each other. So you can’t global in something from one local scope to another. Variables are either global or local.
That much I get and makes sense (and is in the documentation). What threw me for a loop was that PHP won’t copy something into the global scope from a local scope that is already defined **and will happily overwrite your local scope with a null value from the global scope if one doesn’t exist in the global scope, **in the process of creating the variable in the global scope. If you want a variable in the local scope to be global, you have to declare it as global before you write a value to it.
Or, to put it another way: