Global Scope

Scope can be a confusing concept for many beginners in PHP. The idea is that some variables and functions are invisible to each other in certain circumstances of code.

If you declare a variable outside of a function, let's say $C_array. The function cannot see it until you declare it as a global inside the function.

$C_array = array(5,2,1);
function Test(){
  global $C_array; // without this, C_array would be out of scope.
  $C_array[] = 7;
}

Alternatively you can use the superglobal $GLOBALS['C_array'].

Static Variables

Static variables can be useful for recursive functions.

Most variables declared inside a function are in the local scope and they stay there until the function finishes. However, if you restart the function recursively you may want a variable that doesn't just disappear when the function restarts.

function Recursive(){
  static $count = 0; // do not put an expression here.
  $count++;
  if($count < 25){
    Recursive();
  }
  count--;
}

Scope Operator ::

As long as you have a static function in the class, you can call a class's function without having to initiate the class. Just make sure you don't use a function that is pulling variables that were established in the constructor or the class that isn't static.

Post new comment

name
The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.