PHP Variables

Variables are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores

<?php 
  $var = 'Hello';
  $Var = 'India';
  echo "$var, $Var";                 // outputs "Hello, India"
  $1var = 'lorem ipsum';             // invalid; starts with a number
  $_1var = 'lorem ipsum dolor';      // valid; starts with an underscore
?>

PHP is a Loosely Typed LanguageA loosely typed language is a programming language that does not require a variable to be defined.. In the example above, notice that we did not have to tell PHP which data type the variable is. PHP automatically converts the variable to the correct data type, depending on its value.

PHP Variables Scope

PHP has three different variable scopes:

  • local
  • global
  • static

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:

<?php 
  $var = 5;// global scope
  function myTest() {    // using var inside this function will generate an error    
    echo "Variable var inside function is: $var"; 
}
  myTest();
  echo "Variable var outside function is: $var ";
?>

A variable declared inside a function has a LOCAL SCOPE and can only be accessed within that function:

<?php 
  function myTest() {    
    $var = 5;// local scope    
    echo "Variable var inside function is: $var"; 
}
  myTest();
  echo "Variable var outside function is: $var ";
?>

a static variable is a variable that doesn't lose its value when the function exits.

<?php 
function test() {     
  static $var = 0; 
  echo $a;
} 
$a++; 
test(); // prints 0 
test(); // prints 1 
test(); // prints 2
?>