(click anywhere to close)
OPEN MENU

[PHP] Scope

category: Website | course: PHP | difficulty:

Last chapter proved to use that functions kind of live in their own world; they coexist with the rest of the code in a file, but they are only executed once called, and have their own set of parameters. So, the questions that begs asking is: can functions interact with the rest of the code, and if so, how?

For example, what happens if one of our parameters has the same name as a variable declared somewhere else? We could frantically start adding random letters behind parameter names to make them distinct, but that’s not the best way to go. Instead, PHP uses scope.

Scope refers to the part of a program where a certain variable is available

A variable’s scope can be global, local, or static.

Global

Any variable declared outside of a function is automatically global. It can be accessed from anywhere within the program, except from within functions.

function multiply() {
	$x *= 2;
}

$x = 5;
$x += 5;    //Refers to the same $x, $x is no 10
multiply(); //Gives an ERROR, as the function doesn't know the global variable $x

Local

Any variable declared inside of a function is automatically local. It can be accessed only from within that specific function.

This is usually what you want, but sometimes you want to be able to change or use global variables within the function. To do so, you can tell PHP to use the global versions of a variable, with the global keyword:

global $var1, …, $varn;
function multiply() {
	global $x, $y;
	$x *= 2;
	$y *= 4;
}

$x = 4;
$y = 2;
multiply(); //$x and $y are now 8

If you intend on using both local and global versions of a variable (which can be confusing), there’s an alternative syntax. PHP automatically stores all global variables in an array called $GLOBALS, and we can access elements of that array if we want the global version of a variable.

function multiply() {
        //Here, $x is 16
	$x = 16;
	$GLOBALS['x'] *= 2;
}

$x = 4;
multiply(); //Here, in global scope, $x is 8

Static

Lastly, to bridge the gap between local and global scope, there’s static scope. If you define a static variable within a function, it will only be usable within that function but it won't be deleted when the function ends. To do so, simply use the static keyword:

static $var = value;

It is important to note that static variables are only assigned a value if they don’t have a value yet. This is useful, for you can call the same function multiple times, but only the first time is a variable initialized/reset. You can only initialize static variables to a literal value though, not an expression (such as another variable).

//You'd think that the $count variable would be reset each time, but it's only set to zero the first time it's called
function counter() {
    static $count = 0;
    $count++;
    if($count >= 3) {
    	echo "GO!";
    }
}

counter();
counter();
counter(); //Prints: GO!

echo $count; //Prints an undefined variable warning

Static variables are still local to that particular function – you can’t mindlessly use them in other functions.

Constants

This is great, but what if we want like a super-static variable – one that is accessible anywhere? Well, we can’t easily do that. (They do exist, and are called superglobals, but we can’t define them ourselves.) PHP does provide the ability, however, to define a constant that can be used and accessed anywhere.

A constant is nothing more than a variable that can’t be changed. So it’s simply a value that is the same for the entire program, which you can access any place, any time.

To define a constant, use

define("name", value [, case_insensitivity]); const name = value;

If the last parameter is set to true, the constant is case-insensitive. (It’s case-sensitive by default.) Also, the const keyword can only be used in global scope.

To use a constant, you simply call it by its name (without quotes).

function define_my_constant($name, $value) {
	define($name, $value);
	echo "Created constant $name with value $value";
}

//Even though the constant is created within the function, it's accessible anywhere
define_my_constant("PANDA", "I'll Bamboo You!");

echo PANDA; //Prints: I'll Bamboo You!

PANDA = "No, you won't"; //Will give a syntax ERROR - you can't change a constant

Again, constants follow the same naming rules as variables and functions.

References

The only thing that is really tricky when it comes to scope, is applying it to references. We’ve seen that references are a great way to point one variable to another, and they are a great way to bridge the gap between scopes and code blocks. But there's good and bad things.

The Good: You can pass a variable by reference to automatically make it act in the same scope. To do so, simply place the familiar ampersand ( & ) in front of the parameter name.

//This works fine
function echo_user_count(&$count) {
	echo "There are $count users online at the moment";
}

$user_count = 10;
echo_user_count($user_count);

The Bad: Say we declare a variable inside a function (local scope), and assign it a reference to a variable elsewhere (global scope). Well, when the function ends, the local variable would be removed, in which case the global variable would be removed as well. PHP doesn’t want this happening, which means changing referenced variables in a function has no effect.

//This does not work fine. It doesn't give an error, it just does nothing.
function add_user() {
	$count = &$user_count;
	$count++;
}

$user_count = 10;
add_user($user_count);

echo $user_count; //Prints: 10
CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)