PHP globals and their evil nature
While the feature itself is loved by some, it can cause odd issues you should be aware of
I was moving live a site the other day onto a shared hosting server and encountered an error that looked like a total mystery at first glance:
Fatal error: Cannot use object of type MyUser as array in /www/domain.com/public_html/core/modules/MyUser.php on line 7
A snippet from the class where the error occured:
- class MyUser
- {
- public $username = null;
- ...
- public function init()
- {
- ? $_SESSION['user']['username']
- : null;
- }
- }
And a portion of a code where we created an instance of the class:
- $user = new MyUser ();
- $user ->init();
And now let's think what might be actually happening. With register_globals on, the variable $user isn't null but it is the same variable as $_SESSION['user']. However the new instance of the MyUser class is assigned to it, so its' not an array anymore. Later on in the init() method we try to access $_SESSION['user']['username'] which is in fact equal to the statement: $this['username'].
Jesus Christ!!! Multiply this the times you use the same names for objects, variables and global variables and you'll feel the coming of the digital doomsday of your application.
Things can be even funnier in this case. As we're working with the session variable - it's persistent nature will cause that the error will reappear even after turning off register_globals. Until we of course clear or unset the $_SESSION['user'] variable.
So, do yourself a favor - make sure register_globals is turned OFF. If this is not possible for any reason (even after urging the host to do so), use prefixes to distinguish between the variables and make sure any other developer that may work on the particular site knows about this. Oh and If you never heard about register_globals, please visit http://php.net/manual/en/security.globals.php



