PHP – Variable



In PHP Variables are used for storing values such as numeric values, characters, character strings, or memory addresses.

In PHP, a variable starts with the $ sign, followed by the name of the variable.

Rules for PHP variables:

  • A variable name must start with a letter or the underscore character.
  • A variable name cannot start with a number.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($age and $AGE are two different variables)
<!DOCTYPE html>
<html>
<body>
<?php $a = "www.whatsnewtodayworld.com"; echo " $a is a PHP Tutorial"; ? >
</body>
</html>
Output
www.whatsnewtodayworld.com is a PHP Tutorial
<!DOCTYPE html>
<html>
<body>
<?php $a = 20; $b= 10; echo $a + $b; ? >
</body>
</html>

Output

30

Note- Variable name are user defined. You can take any name as your choice.

PHP has three different variable scopes:

  • local
  • global
  • static

Local Variable scope

A variable declared within a function is called as LOCAL SCOPE and can only be accessed within that function.

<!DOCTYPE html>
<html>
<body>
<?php function myTest() { $a = 10; // local scope echo " Variable a inside function is: $a "; } myTest(); // using x outside the function will generate an error echo " Variable a outside function is: $a "; ? >
</body>
</html>

Global Variable scope

A variable declared outside a function is called as GLOBAL SCOPE variable and can only be accessed outside a function:

<!DOCTYPE html>
<html>
<body>
<?php $a = 10; // global scope
function myTest() {
// using a inside this function will generate an error
echo "

Variable a inside function is: $a

";
}
myTest();
echo "

Variable a outside function is: $a

";
? >
</html>

Static Variable Scope

A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.