Understanding Scope

Author Topic: Understanding Scope  (Read 507 times)

Offline chinmay.sahooTopic starter

  • Trade Count: (0)
  • Full Member
  • ***
  • Thank You 2
  • Posts: 139
  • Karma: 0
    • No Addiction
Understanding Scope
« on: 07-02-2016, 05:54:13 »
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:

// 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.


Related Topics

  Subject / Started by Replies Last post
0 Replies
Last post 08-20-2011, 00:05:09
by Vinil
0 Replies
Last post 09-10-2011, 10:29:05
by Maddy
4 Replies
Last post 07-06-2012, 05:02:21
by jamesdavid
0 Replies
Last post 07-12-2012, 03:53:11
by googinup
0 Replies
Last post 09-07-2016, 05:24:14
by beingchinmay