PHP 7 Variables




What is PHP Variable?

PHP variable a name of memory location that save or holds information or value or data like strings, arrays, numeric value, objects, characters, etc. The PHP variable is a temporary storage that is used to store data temporarily. In PHP, basic variable is declared using "$"" sign followed by variable name.

How to Declare or Create Variables in PHP?

You can see the below, how to declare or create variable in PHP.


    $name = 'string'; // string varible
    $a = 5; // int type variable

Important Notes for PHP variables:

  • A variable starts with the "$" sign, followed by the name of the variable
  • A variable name cannot begin with a number
  • A variable name must begin with a letter or underscore character
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _)
  • In PHP, Variable names are case-sensitive like e.g. $name and $NAME

PHP: Loosely typed language

PHP is a loosely typed language, that means PHP automatically converts the variable to its correct data type.

PHP Variables Scope

The PHP variables can be declared or created anywhere in the code or script. There are three different variable scopes in PHP. See below:

  • PHP local Variable Scope
  • PHP global Variable Scope
  • PHP static Variable Scope

PHP Local Variable Scope

A local scope is a restricted range of variables within which a code block is declared. That block can be a function, class, or any conditional period. Variables within this limited local scope are known as local variables of that specific code block.

$abc = 'Hello Word'; 

//explain local variables scope

function localValFunction() 
    // This $abc is local to this function 
    $abc = 'hello developers'; 
    echo "$abc \n"; 
// $abc outside function localValFunction() is a  
echo "Variable abc outside localValFunction() is $abc \n"; 

PHP Global Variable Scope

As its name, the global field provides wide access to variables declared in this scope. Variables in the global scope can be accessed from outside a function or class independent of its range.

$abc = 20; 
//explain global variables scope
function globalValFunction() 
    // the variable $abc to access within  
    global $abc; 
    echo "Variable abc inside function : $abc \n"; 
echo "Variable abc outside function : $abc \n"; 

PHP Static Variable Scope

It is a feature of PHP to remove variables, it completes its execution and memory is freed. But sometimes we need to store the variable even after the completion of the function execution. To do this we use the static keyword and the variable is then called a static variable.

//explain static variables scope
function staticValFunction() 
    // static variable 
    static $num = 76; 
    $sum = 88; 
    echo $num, "\n"; 
    echo $sum, "\n"; 
// first function call 
// second function call