admin wrote:Compared to this, my way of prefixing $g_ is clear and fool-proof as can be. And yes, I prefer to use $g_ instead of just $_. It's a touch more explicit, and also kind of reminds you that globals are bad.
Now why would you say that, global vars will be great and allow me to remove lots of unnecessary getkey/setkey and copytext/<clipboard>, thus also giving me back my status messages!
That's not bad at all!
And I'm not sure what confusions you were referring to, I feel PHP's way is quite easy, and even better actually, because no variable is ever global, it's only global when you want it to be. That means imagine a script using a global var $foo and then loading another script also using $foo, that second script could use $foo without it being a global var, it can decide whether it will be local or global.
Sure, variables don't say whether or not they're global by their names, but is that really a problem ? Everyone can still decides to make it that way... Look at your PHP or VB code and tell me, can you tell which vars are global and which are local just by their names ? Answers might be yes, but only if you decided to use a rule for it, shall it be a prefix, a suffix, uppercase for global and lowercase for local, etc
Just like maybe your variables are names "nbSelectedItems" or just "d", no one forces you to use names that actually allow to easily "understand" what the variable is, but no one prevents you from doing it either.
As for your original questions, I think they all have easy and logical/"natural" answers :
- Can local and global vars have the same name and live independently?
hm.. okay, yes and no. A variable is either local or global, and you obviously can't have two variables by the same name. But a script can use local vars with names of existing global vars without problem/conflict, since it doesn't access those (global vars) unless it asks for it (using command global), and then it will use the specified global var, so no more local one.
- Which one dominates the other if there are same-named vars?
There's no dominance. A script using $foo uses a local var $foo until a call to global for $foo is trigered. Then, local $foo is unset and global $foo is "loaded"/used instead.
- Can a local var be globalized later in the script?
Sure, why not.
Code: Select all
"script1"
$foo = 4; // local
global $foo; // now $foo is global, becomes empty (assuming nothing created a global $foo before obviously)
$foo = 8; // global
sub script2;
msg $foo; // 16 (global)
"script2"
msg $foo; // nothing/empty, it's local
$foo = 15; // local
global $foo; // global, value is now 8
$foo = 16; // global
My order of preference would be:
1. no name-specific but command global (PHP-like)
2. $_name
3. $g_name