PHP Variables
As PHP is a loosely typed language, so we do not need to declare the data types of the variables.
It automatically analyzes the values and makes conversions to its correct datatype. After declaring a variable, it can be reused throughout the code. Assignment Operator (=) is used to assign the value to a variable.
Type-1
Local variable or user defined variable.
Type-2
Global variables or pre-defined variables
a) $GLOBAL => To create a php global variable.
b) $_POST => To access value from a HTML form using 'post' method.
c) $_GET => To access value from a HTML form using 'get' method.
d) $_REQUEST => To access value from a HTML form using any method.
e) $_SERVER => To get data related to server.
f) $_SESSION => To create session storage.
g) $_COOKIE => To create a local storage.
h) $_ENV => To get or update data in PHP environment.
i. $_FILES => To access file details from a HTML form and upload to the server.
What are the rules to declare variable in PHP?
- It must start with the dollar sign.
- There is no need of data type (int, float, char) to define a variable.
- Variables can, but do not need, to be declared before assignment.
- After the dollar sign, the first letter of a variable should be alphabet or underscore(_).
- After the dollar sign, the first letter of a variable should not be a digit.
- After the first character, it may be a combination of alphabets and digits.
- Blank spaces are not allowed in variable name.
- A variable must start with a dollar ($) sign, followed by the variable name.
- It can only contain alphanumeric character and underscore (A-z, 0-9, _).
- A variable name must start with a letter or underscore (_) character.
- A PHP variable name cannot contain spaces.
- One thing to be kept in mind that the variable name cannot start with a number or special symbols.
- PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.