Variables are the identifiers of the memory locations that are 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' values may change during execution. If you declare a variable in PHP, that means you are asking the operating system of the web server to reserve a piece of memory with that variable name.
Variable Definition and Initialization
We can create different types of variables, such as 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.
Example:
<?php
$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 are 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 need to declare data types, because PHP automatically converts variables to data types depending upon their values.
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 underscores, such as (a-z, A-Z, 0-9 and _ ).
- The variable name can not contain 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:
Example:
<?php
$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:
Example:
<?php
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 they can make it complicated to understand and document your code, but also because their improper use may lead to critical security issues.