Jump to content

Functions and global variables


cloudll

Recommended Posts

Hey guys.

 

I have been reading into global variables and its confusing me. I am trying to understand the best way to go about using variables within a function.

 

I have been using the following format

$var1 = "blah";
$var2 = "blah";

        function phpfreaks()
	{
	global $var1, $var2;

	echo $var1;
	echo $var2;
	}

The internet seems to hate variables used this way with a passion. Surely its okay for something like the PDO $dbh to be used as a global variable as this will never be changed?

 

I'm still a big novice at all of this, would someone be able to edit my example please to show me the best approach to using external variables in my functions?

 

Thanks for any help

Link to comment
https://forums.phpfreaks.com/topic/296554-functions-and-global-variables/
Share on other sites

The reason global variables are bad, is because they can change.  What happens if you start coding a new script and call the PDO variable $pdo instead of $dbh?

However there are much better ways of doing things.

$var1 = 'blah';
$var2 = 'blah';
 
function phpfreaks($v1,$v2) {
 return $v1 . ' ' . $v2;
}
 
echo phpfreaks($var1,$var2);

If you want to make sure the correct type of variable is passed to the function, you can use type hinting.

$var1 = 'blah';
$var2 = 'blah';
 
function phpfreaks(PDO $v1, $v2) {
 return $v1 . ' ' . $v2;
}
 
echo phpfreaks($var1,$var2);
//return: error, as $v1 is not an object of PDO

You can also pass by reference, so that the function has control of the variable outside of the function scope.

$var1 = 'blah';
$var2 = 'blah';
 
function phpfreaks(&$v1, &$v2) {
 $v1 = 'Not Blah';
 $v2 = 'Not Blah';
 return;
}
 
if(phpfreaks($var1,$var2)) {
 echo $var1 . ' ' . $var2;
}
//output: Not Blah Not Blah

Pass them as arguments and have what you read about globals clinically erased.

function phpfreaks()
{
    global $pdo;
    ...
    return;
} 

is fine until the day comes when you find yourself having to work with two simultaneous PDO connections, and all your functions are wired in to the first. Now you have to start swapping values.

 

If you had used

function phpfreaks($pdo)
{
   
    ...
    return;
}

there would be no problems.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.