PHP Variables and their scope

PHP Variables are the placeholders of values to be used in a program while execution. They are actually names given to the memory locations that hold the value entered while execution,  initialised in the program or calculated by a formula. It is essential to understand PHP variables and their scope to create effective PHP codes.

Characteristics of PHP variables

  • Always declared preceded by $ symbol, does not allow space or special characters in variable names except _(underscore)
  • Cannot begin with a number.
  • No need to assign data type to a variable. The most recently assigned value defines the data type of a variable. It also means that you can assign one data type value to a variable and reassign value of different data type within same code.
  • Variable declaration is not at all required before using it. This feature makes PHP a loosely typed programming language.
  • Variable value is assigned with an assignment operator ‘=’. RHS value of the assignment statement can be a constant or expression.
  • Variable contents can be emptied by using unset() function or assigning it ‘NULL’ value. NULL is not same as 0 or an empty string.
  • PHP provides a function to check whether a variable is assigned a value or not. It can be done by using isset() This function returns a Boolean value. If the variable is assigned a value isset() will return ‘true’ else ‘false’

Some correctly declared PHP variables -$FirstName, $myVar, $perm_address

Some incorrectly declared PHP variables– $First Name, $my.Var, $1address.

PHP variables scope

PHP variables scope defines the availability and meaning of a variable in different sections of a program.

  • A variable defined within a function is local to the function since its value will be retained within same function. If another function contains a variable with same name, its scope will be local to this function.
  • A variable declared at the beginning of a php file before any other function declaration, is global for all functions. If a variable of same name is declared inside a function, the local variable will override the value of global variable.
  • Variables assigned with same name in different php files of same project or module are different. Their scopes are local within their containing php files.