|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2002-03-20 09:51 UTC] adam at adeptsoftware dot com
"In PHP global variables must be declared global inside a function if they are going to be used in that function." I really think PHP should not be different from C here - or at least there should be a setting for this. Even something like "global ALL;" would be better, but not ideal. The most common problem I run into by FAR is variables not being available in the local scope. Making me register 20 of them as global by name in every single function is counterproductive and goes against the idea of keeping code as simple as possible. Your justification for this is: "This can cause some problems in that people may inadvertently change a global variable." That is a very rare problem compared to the new problem this has introduced. JavaScript handles this better, requiring declaration with "var" to force a variable to be local only. I would much prefer this, and PHP doing it the way every other language does would also be preferable. PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 23 20:00:01 2025 UTC |
I agree with Rasmus (and I really like his story :-), but to help you shoot yourself in the foot: Declare and use your globals like this: $g->id = 1000; $g->username = "Marc"; // etc. until you have 20 of them function fn() { global $g; $g->username = "Rasmus"; } with the added benefit of auto-global for any new global var you add in a later stage of the project. This looks very similar to using $GLOBALS["username"] inside your function, which is what I use if I desperately _need_ a global. Cheerio, Marc.Interestingly, the one-line solution for accessing globals seems to be causing PHP.exe to hang. I have narrowed it down to the following code which makes php die under WinXP (at least it does here) <? session_start(); session_register("Ses"); $Ses->UserAdvanced = true; function test() { foreach($GLOBALS as $key => $value) global $$key; // get access to all globals } test(); ?>