Global and Local Scope in PHP
Global and Local scope in applications programming is a crucial aspect that needs to be properly understood. Particularly the global aspect.
So what does global mean in a programming context?
Global means that data or logic can be accessed anywhere in the application by anything without restriction. On the face of it this seems to make sense – arguably it means less code. However – the problem with that is any data that is set globally can be changed.
Imagine if you had written a shopping cart application that had a specific delivery rate. Now, if you set the delivery rate as a GLOBAL variable and a function call was made to apply a different delivery rate to a specific product using the GLOBAL delivery variable already set and you changed the value of that GLOBAL variable it will remain changed so when applied as the normal delivery rate you will end up with an error not to mention some very disappointed customers!
What are the alternatives to GLOBAL?
Tip: Try not to use global variables at all but instead pass variables as parameters in function calls
If you must use globals PHP has a method for global scoping of variables. This is using the $GLOBALS array or keyword global. What it can do is access variables outside the scope of a function and modify them within the function.
Let’s see it in action
// This example uses a callback function. $cost = 5; $shipping = 10; //Watch the total cost figure $total_cost = 10; function addShipping() { global $total_cost, $cost, $shipping; $total_cost = $cost + $shipping; } addShipping(); echo $total_cost . ""; //Using the $GLOBALS keyword function addShipping2() { $GLOBALS['total_cost'] = $GLOBALS['cost'] + $GLOBALS['shipping']; } addShipping2(); echo $total_cost;
Local Scope
Local scope is the way forward for most applications. Essentially variables can be changed and accessed only within the scope of the code block. Sound familiar? Well, it should do because what we are talking about is functions! If we were to go back to our original delivery example if we wanted to set a rate specific to a product a function might have been a viable option:
function deliveryRate($productValue) { $deliveryRate = 0; $rateA = 3; $rateB = 5; if($productValue <= 50) { $deliveryRate = $rateB; } else { $deliveryRate = $rateA; } return $deliveryRate; }
Another advantage with using local scope and avoiding globals all together is security. By encapsulating your data within a specific local scope it prevents accidental or wilful manipulation of global data.
But what happens if you must have a global var?
Well actually there is a technique that you could use its called define. Say you had a variable for sales tax...
define("SALES_TAX", 21);
Unless you change the value within the define it cannot be altered. But be careful - use with care!!