Search the Community
Showing results for tags 'globals'.
-
PHP Fundamentals II: Globals and Superglobals Welcome back to PHP Fundamentals! Let's head on forward in our learning PHP basics. For this guide, we'll go over the queens and kings of variables: globals and superglobals. If you'd like to follow along, and play with these concepts yourself as you learn them, check out phptester.net -- this is a PHP sandbox free for general public use, that you can use to test PHP coding and see the results immediately, without needing a test server of your own. … well, not that there's much to play with, here. Let's get started! WHAT IS A GLOBAL? Last time, we learned what a variable is, how to define, and how to use one. Variables, by default, are only usable in the file they are defined in. So, if you define $variable in mytest.php, you can only use it in mytest.php. Further, because of script scope, if you define $variable in a function, it is only usable in that one function, and not elsewhere in the file! But what if you're building a script, a full, cohesive PHP software? At some point, you're going to need to use variables in other files, and redefining them every time you need them just slows everything down, and it's not terribly pretty, either. It's good to understand the core logic behind PHP script building, because it helps you extrapolate what, most likely, your chosen software's back-end operates like. This is what globals are for. At the top of PHP functions in a typical script, you'll probably find a global line. Globals are activated in files by adding them to an aforementioned global line, in most cases in the base file that the PHP script core comes around (usually index.php or something like), outside of a function (so that the global triggers for the entire file). They're always available for use, but you have to call them in the global line for them to be usable. This is to prevent all the globals, which may be quite numerous, from being active at once and using up a lot of memory. Only activate the ones you need! I've seen a lot of people pull gigantic global arrays into their files just for one thing (PLEASE STOP THAT, YOU HURT ME and your RAM, you know, psh). If you can, find another way of getting that one thing, if that's really the only thing you need, as it can impact server resources and page load times. Unless you really want your site to make your server eventually cow, far be it for me to stop self-sabotage. DEFINING A GLOBAL Much of the time, there is a main controller file somewhere in a PHP script that declares variables global, on a global line, and then defines those globals in that controller file. For instance, SMF's Load.php will define $context as a global and then add things to that variable. $context is a very gigantic array, and has a lot of data in it, which is used in basically every file in SMF (if you work with SMF, get used to it). To fully understand how this works, let's go over scope. Scope is defined as what data a particular PHP file or function has access to. Outside of a function, the file has access to only what is defined within itself. Ergo, if you start the file out like this: $variable = 'This string can be used in the entire file.'; You'll be able to echo $variable across the file freely, barring in functions. Functions have their own scope; they're sort of like mini-files within a file. If you were going to use $variable later down the road, in a function, you'll want to make $variable global. You do this by adding global $variable; To the top of the file before $variable is given a value. Now, you can call $variable in a global line at the start of a function, and echo out its value through the entire function. In a PHP script, you'll also have a lot of files included into another one; most often in the index.php file, generally, you'll have several back-end source files included in it. These files have their own scope, but you can use their globals, as well, in both the file they're included in, and the other files included with them. So, say in index.php we include File1.php and File2.php. Both have globals defined. File1 has $variable1 and $variable2, and File2 has $variable3 and $variable4. $variable1 and $variable3 are globals. This means, File1 can use $variable3 by pulling it in global line, but cannot use $variable4. Congratulations, you now understand the basics of how to construct a full-fledged, multi-file PHP script. USING A GLOBAL Global variables are used very similarly to variables in general. Remember to declare them in a global line if you're in a function or a new file, and then just echo them out, or use them in place of transient data. Most often, you'll probably be working with user information, and this is most likely already declared a global within the scope of the script, so you just add the global line and call the global variable, and use away. If, ever, you are unsure of what data is in a specific global, and need to know (some globals alter their data based upon which file they're being used in), you can do: echo '<pre>',print_r($globalvariable),'</pre>'; We talked about print_r() a bit in the last PHP guide, but what's it do exactly? Essentially, it echos out the contents of an array. If you're ever unsure if a variable is an array or not, start with print_r(). The pre enables the echo'd array to arrange itself in a more readable manner, so you end up with a pre-formatted, list-like result of every piece of data in an array, and what its keys and values are. Say you echo out uh shoot, how about $context. It will give you something like this: Array ( [user] => Array ( [id] => 1 [is_logged] => 1 [is_guest] => [is_admin] => 1 [is_mod] => [can_mod] => 1 [is_subaccount] => [username] => registeredname [language] => english [email] => emailaddress@goeshere.com [ignoreusers] => Array ( ) [warning] => 0 [unread_mentions] => 0 [birthday] => 1990-02-22 [age] => 28 [unread_bookmarks] => 0 [new_errors] => 0 [group_requests] => 0 [topic_reports] => 0 [name] => Esmera [smiley_set] => none [messages] => 1 [unread_messages] => 0 [popup_messages] => ) ) There's a lot more to this array, but you get the idea. This tells you that you can echo $context['user']['email'], and it will output 'emailaddress@goeshere.com'. Nifty, huh? (Yes, this is part of my SMF's $context['user'], there will be things in there that aren't on any other SMF install, because I modified the back-end to load some extra things.) SUPERGLOBALS Oh, the fun stuff! Superglobals are variables that are available in PHP, regardless of whether they are defined as a global or not (thereby, you don't need to). Primarily, these are core function-specific variables, that PHP absolutely needs to operate, such as $_SERVER; this variable contains various items regarding the connection between user and server, as well as some important server information. We also have $_REQUEST, $_GET, $_FILES, $_POST, $_COOKIE, $_SESSION. Any time a variable prefixes with an underscore, you're using a super global. $_SERVER contains server and execution environment information. Headers, paths, script locations, etc, but some servers may not create these superglobals. $_REQUEST contains the contents of $_GET, $_POST, and $_COOKIE. Essentially it looks for anything in these three other superglobals and uses the first positive match it finds. I believe it goes through $_POST first, then $_GET, then $_COOKIE. $_GET contains URL parameters. If you've ever seen a URL that ends with something like tid=872, this is a URL parameter. This is available to the PHP script via $_GET['tid'], the value of which would be 872, here. This, most likely, is how forum softwares determine what thing to load and when. SMF, for instance, uses URL parameters for… basically everything it does, actually, as it uses URL parameters to decide what to display on a page. $_FILES contains information about file uploads that are sent to the server. Yes, your file information is separate from your post information, I know that's weird, but the server needs some more information about file uploads than a typical post array can offer (and trying to sub-array in $_POST tends to just confuse it, for the record). $_POST contains posted data. When you create an HTML form that operates with PHP, most likely, it will send through method="post" - that references $_POST. All fields in an HTML form is thus accessed via $_POST. There'll be a guide that goes over PHP, forms, and their love hate relationship with each other (honestly, they need marriage counselling). $_COOKIE contains an array of variables that are sent to the script via HTTP cookies. There will most likely never be a reason for you to mess with this one, so just know it exists. $_SESSION contains session variables that are used by the script. This probably doesn't make sense, don't bother trying to make sense of it right now, just smile and nod. This early on, you have no reason to use $_SESSION or $_COOKIE, most likely the script/forum software itself has another means of doing this without using the superglobals (do it the way your software does, because there are security reasons as to why it does it that way - go with it, Crispy). If you're ever unsure if you need $_POST or $_GET, you can use $_REQUEST. If you're unsure if you need $_POST or $_FILES, remember, standard form data is in $_POST. Uploaded file information is in $_FILES (for the love of Hemsworth, please don't start making your own file uploaders until we've gone over the security aspects). Alright, so we got a firmer idea of how variables can be used as globals, and what superglobals are and what they're for. Next guide, we'll take a deeper look at arrays, and how to create and use one. This is where it gets fun! Get excited! I know I am!