Main Content

Global - Tcl, PHP, Python

Archive - Originally posted on "The Horse's Mouth" - 2008-09-03 00:23:43 - Graham Ellis

PHP, Python, Tcl and a number of other languages have a global keyword. And it's a misnomer in most (if not all) cases.

To the un-initiated, "Global" means "worldwide" or "shared all around". So you would think that if you declare something as global, you're going to be sharing it with the same thing everywhere else. But - sorry - that's not the case. In each of the languages I quoted, global really means "Share this with the variable of the same name in the main program".

What does this mean?

• In Tcl, Python, PHP ... you do NOT need to declare a variable as being global in your main code, even if you want to share it with your procs (Tcl) methods (Python) or functions (PHP) - it is, in effect, automatically global if you want to declare in global in a named block of code

• If you don't want a variable within a named block of code to be shared with the same 'global' variable, you can be reassured that you will not be sharing it simply by omitting any global declaration for it in the named block

• If you want to share a variable between two named blocks of code, you can do so by declaring it as global in BOTH of them ... and this has the side effect that it will also be shared, without any declaration, by any variable that happened to have the same name in your main block of code