Jump to content
Larry Ullman's Book Forums

Overusing Global Variables: Are They 'Bad' ?


Recommended Posts

Hello Larry,

 

From my first encounter with PHP (from your various books) I've always understood that if one needs to use a variable in a function, when that variable was originally declared outside the function, then it must be declared as 'global' within the function. Similarly if a variable is created within a function and is required outside, it must be declared 'global' within the function (or 'returned'). (It may be that declaring it as global when originally declared also works, but I've not habitually done that)

 

That has sometimes led me to declare a whole raft of variables as global at the start of a function. For example when I have a function to extract a lot of values from a MySQL database. Fairly obviously I want those values to be available outside the function. This can get cumbersome, and I'm sure I've declared globals I didn't actually need, just to be on the safe side.

 

So I've been looking for ways to avoid 'globals' where possible. One way is to return an array of the variables and extract them. Some can be made arguments to the function, etc.

 

In looking around forums and asking questions, it's become clear that a many people consider globals as 'bad' and to be avoided at al costs. Many of the solutions for doing so require OOP. I'm not yet comfortable with OOP (it's hard to find time to learn). So pro tem I'm stuck with procedural coding.

 

For example, here's the start of a function to calculate the cost of a family staying at our Bed & Breakfast. The variables are those entered by the visitor to our web site when booking. Some will be zero (or empty or NULL).

function calcBandbCost($link, $setYr, $rate) {
   global $nights, $adults, $teens, $child2, $child1, $baby, $cot_req;
...
   return $bb_cost; // an array with two items
}

The variables are in the main script (from $_POST), but I have to get them into the function. This seems the easiest way. I could extract $_POST in the function, but it contains other variables not neede by the function.

 

I wondered what you thought about it ?

 

 

Link to comment
Share on other sites

The trick is to pass the variables into the functions as parameters. As an example, you'll need to pass the MySQLi object into a function - or declare it global as you're currently doing - to make use of it inside the function.

 

Let's create an example:

// Global way
$mysqli = new mysqli(.....); // Create a MySQLi object

function getUser( $id )
{
    global $mysqli;

    $result = mysqli->query(""); // Use $mysqli here.
}

// Passing variables
$mysqli = new mysqli(.....); // Create a MySQLi object

function getUser( $mysqli, $id )
{
    $result = mysqli->query(""); // Use $mysqli here.
}
Link to comment
Share on other sites

Global variables are "bad" for a couple of reasons. For one, they increase the possibility of bugs because a global variable's value can be changed anywhere. Second, they reflect bad design. Ideally functions should be like black boxes. They should work without knowledge of what's going on outside of them. At the very least, this makes the functions more reusable. When you rely upon global variables, your functions lose their portability. 

 

Although I'm not 100%, universally against using global variables, the fact is that they can easily be avoided by passing the values as parameters.

  • Upvote 1
Link to comment
Share on other sites

Guest Deleted

You can use an array to pass a lot of paramaters to a function.

 

First you have to change your function:

//Add the $values paramater at the end:
function calcBandbCost($link, $setYr, $rate, $values) {

//Add this part:
foreach ($values as $key => $value)
{
$$key = $value;
}


...

return $bb_cost; // an array with two items
}

When you use the function, make sure you 1) have the array already defined and 2) that you give it to the function in the 4th paramater:

$values = array(
'nights' => $nights,
'adults' => $adults,
'teens' => $teens,
'child2' => $child2,
'child1' => $child1,
'baby' => $baby,
'cot_req' => $cot_req
);

echo calcBandbCost('http://www.whatever.com', '1996', '5.95', $values);

Notes:

 

What I put for the first three parameters was just an example. You can put whatever you want.

 

You don't have to use echo. Use whatever you were using before.

Link to comment
Share on other sites

Thank you for your replies.

 

Passing a variable as a parameter is fine, but if (as in my case) you have many variables you either need to pass in or return, it can get cumbersome. The solution is to use arrays as Buttercream Cupcake says. I knew about using an array for 'return', but I hadn't realised one could also use an array as a parameter.

 

BTW, I've come accross a PHP function 'compact' which I didn't know about before, for making an array out of existing PHP variables, so Buttercream Cupcake's example would become:

$values = compact('nights', adults', 'teens', 'child2', 'child1', 'baby', 'cot_req');

Works a treat, and saves a lot of typing, including the awkward '=>' (requiring the shift key).

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

×
×
  • Create New...