Understanding Scope

Started by chinmay.sahoo, 07-02-2016, 05:54:13

Previous topic - Next topic

chinmay.sahooTopic starter

Write more than a few hundred lines of procedural PHP code and, no doubt, you'll run into a parser error or, worse still, a mysterious bug caused by your accidentally having used a function or variable name more than once. When you're including numerous files and your code grows increasingly complex, you may find yourself becoming more paranoid about this issue. How do you stop such naming conflicts from occurring? One approach that can help solve this problem is to take advantage of scope to hide variables and functions from code that doesn't need them.

A scope is a context within which the variables or functions you define are isolated from other scopes. PHP has three available scopes: the global scope, the function scope, and the class scope. Functions and variables defined in any of these scopes are hidden from any other scope. The function and class scopes are local scopes, meaning that function X's scope is hidden from function Y's scope, and vice versa.

The big advantage of classes is that they let you define variables and the functions that use them together in one place, while keeping the functions hidden from unrelated code. This highlights one of the key theoretical points about the object oriented paradigm. The procedural paradigm places most emphasis on functions, variables being treated as little more than a place to store data between function calls. The object oriented paradigm shifts the emphasis to variables; the functions "back" the variables and are used to access or modify them.

Let's explore this through an example:

Quote<?php
// A global variable
$myVariable = 'Going global';
// A function declared in the global scope
function myFunction()
{
// A variable in function scope
$myVariable = 'Very functional';
}
// A class declared in the global scope
class MyClass {
// A variable declared in the class scope
var $myVariable = 'A class act';
// A function declared in the class scope
function myFunction()
{
// A variable in the function (method) scope
$myVariable = 'Methodical';
}
}
?>

In the above example, each of the $myVariable declarations is actually a separate variable. They can live together happily without interfering with each other, aseach resides in a separate scope. Similarly, the two myFunction declarations are two separate functions, which exist in separate scopes. Thus PHP will keep all of their values separate for you.