PHP Variables

Variables are used to store information, like numbers, strings etc. The value of a variable can change over the course of a script. In PHP, there is no need to declare a variable before assigning a value to it. PHP automatically assign correct data types to the variables depending on their values.

Declaring PHP Variables

In PHP variable can be declared as: $name = value;

Example

<?php
$int = 7;
$txt = “Some text”;
$float = 7.5;
?>

PHP has no command for declaring a variable. It is created the moment you first assign a value to it.

PHP Variable Name Rules

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

PHP Variables Scope

The scope of a variable is the part of the script where the variable can be referenced/used. Variables can be declared anywhere in the script. PHP has three type of variable scopes.

  • local
  • global
  • static

PHP Local Variables

A variable declared within the body of a function is local variable and can only be accessed within that function.

Example

<?php
function myVariable() {
$var = 10;
echo “Variable var inside function is: $var”;
}
myVariable();

echo “Variable var outside function is: $var”;
?>

PHP Global Variables

A variable declared outside the body of a function is global variable and can only be accessed outside a function.

Example

<?php
$var = 10;
function myVariable() {
echo “Variable var inside function is: $var”;
}
myVariable();

echo “Variable var outside function is: $var”;
?>

PHP Variables global Keyword

The global keyword is used before variables inside a function to access a global variable inside of a function.

Example

<?php
$var = 10;
function myVariable() {
global $var;
echo “Variable var inside function is: $var”;
}
myVariable();

echo “Variable var outside function is: $var”;
?>

PHP Static Variables

All the values of local variables are deleted after the execution of a function. The static keyword is used to make local variables retain their values after the execution of a fuction.

<?php
function myVariable() {
static $var = 10;
echo $var;
echo “<br />”;
$var++;
}

myVariable();
myVariable();
myVariable();
?>