PHP Variables

Variables are the identifier of the memory location, which used to save data temporarily for later use in the program.

The purpose of variables is to store data in memory for later use. Unlike PHP Constants which do not change during the program execution, variables value may change during execution. If you declare a variable in PHP, that means you are asking to the operating system of web server for reserve a piece of memory with that variable name.

Variable Definition and Initialization

We can make any variable types, like numbers, text strings, and arrays. All variables in PHP start with a $ dollar sign, and the value can be assigned by using the = assignment operator.

   $me = "I am David";
   echo $me;
   $num = 24562;
   echo $num;
   $name = "David";  //Valid variable name
   $_name = "Alex";  //Valid variable name
   $1name = "Jhon";  //Invalid variable name, starts with a number
  • PHP Variables are case sensitive, variables always defined with a $, and they must start with an underscore or a letter (no number).
  • In PHP, unlike other languages, variables do not have to be declared before assigning a value.
  • You also don't require to declare data types, because PHP automatically converts variable to data types depends upon its value.

There are some rules on choosing variable names

  • Variable names must begin with a letter or underscore.
  • The variable name can only contain alphanumeric characters and underscore such as (a-z, A-Z, 0-9 and _ ).
  • The variable name can not contents space.

PHP Variable Variables

In PHP, it is also possible to create so-called variable variables. That is a variable whose name is contained in another variable. For example:

   $name = "me";
   $$name = "Hello";
   echo $me; // Displays Hello

A technique similar to variable variables can also be used to hold function names inside a variable:

function testFunction() {
   echo "It works.";
$funct = "testFunction";
$funct(); // will call testFunction();

Variable of variables are very potent, and variable should be used with care because it can make complicated to understand and document your code, but also because of their improper use may lead to critical security issues.

How to create and use PHP variables