Main Content

Global, Superglobal, Session variables - scope and persistance in PHP

Archive - Originally posted on "The Horse's Mouth" - 2006-11-21 16:46:39 - Graham Ellis

"Global" is a poor choice of word! It really means "share this variable in this function with the variable of the same name at the top level" but there isn't a simple, easy better word for that than "Global". If you bring in code within an include / require file, then any top level code's variables in there will also be in the space that will be shared by any global declarations within the functions.

Superglobals are variables like $PHP_SELF, $_REQUEST, and $_SERVER. They are so called because they're always available in any functions without you having to make a global declaration. However, once again they do not persist between pages in a session, with the singular exception of $_SESSION as described in the next paragraph.

(Super)global variables of this type do NOT persist between successive pages of a session - the (modern) way for a variable to persist in that way is to (a) have a session_start() call in your code and (b) save the value you want to retain in the $_SESSION superglobal.

The other way to retain information between pages in a session is to bounce the information required via the browser - either in the form of hidden fields, a URL rewrite, or a cookie. That's really how $_SESSION works, but it's hidden from the programmer at the low level, and the information bounced via the browser is a single value which equates to a file name or database row key which can in turn be used to pick up all the other saved (session) values on the server.

It has been suggested that rather more than just these variables can be stored between pages, as database connection sometimes appear to persist rather than be refreshed every time. This is rather different - PHP routines like mysql_pconnect will make a persistent connection which will be stored in a pool of open connections once a page is completed. Then the already existing connection can be reused by a subsequent page which may, or may not, be a part of the same session.