6. Variable and Its Scope

Variable is a namespace which can store some value. Variables called by its name and its values can be update line by line. To create a variable in PHP you must know these rules.

Rules for Variables:

  • A variable name started with a $ sign followed by name (Example : $myvariable).
  • Name can contain only alpha-numeric and underscores (Means :  a-Z, 0-9 and _).
  • Its name can’t be start with number and there is no space in name.
  • Name is case sensitive (means : $name and $Name are different variables.)
  • You do not need to define data-type because it does by PHP itself

Variable Scopes

Scope defined the range of availability a variable. In PHP there is there scopes.

Local Scope

If you declare variable in a function it can be called within that function from outside of that function you can’t call that because it has local scope and it work locally.

Example:

<?php
    function test(){
         $check = 10;
         echo " <p>called check inside test function is = $check</p>";
    }
    $check();  // here we call test function .
    echo "<p>called check outside test function is =$check</p>";
    //if we call check outside the test function is show a error.
?>

Global Scope

If you declare variable outside function its scope is global. So, it can be called outside of function globally but not inside a function if we want to it inside the function we need called it as global by using global keyword .

Example :

<?php
      $check = 10;
      function test(){
          echo " Variable check called inside test function without global scope is = ";
          echo $check."<br>";
          //its show a error because $check is not within function. so we need to call it globally.
          global $check;   // here we use global variable $check using global keyword.
          echo "Call check with in function but with global scope is =$check";
      }
      $check();  // here we call test function .
      echo "<p>call check outside test function is =$check</p>";
?>

Static Scope

Normally when a function is execute/called then it all variables delete. if we want to keep it for further use we make it static. A local variable with Static scope no deleted after use.

Example :

<?php
     function count(){
         static $y = 1;    // static keyword used for static scope
         echo $y;
         $y++;
     }
     count();
     count();
     count();
?>

Please run above example on more time without static keyword for check difference.

Leave a Reply