PHP Variable

PHP variable is a container for holding one or more values.
Variables are used to store integers, float, string, etc value.
Variables are represented as:

Example:

There is no need to give data-type of variable, parser itself determines the data-type of variable at run time depending on value.
Variables inside double quotes(” “) are evaluated for their values.
Example:

From above example, we can say PHP is Loosely Typed Language.
You can define variable value within single quotes(‘ ‘) or double quotes(” “).
 

Rules for naming variable name:

  • Variable name is always start with dollar sign($).
  • Variable name is case-sensitive.
  • A variable name must start with a letter(a-z, A-Z) or the underscore(_) followed by any number of letters, numbers, or underscores.
  • A variable name cannot start with a number

Example:

Here $name and $Name are considered as different variables because PHP is case-sensitive language.
It is not necessary to initialize variables in PHP.
 

Default values for variables

If you do not initialize variables then they will be initialized by default value of their type depending on context.
A Default value for integer type data is zero.
Default value for floating type data is zero.
A Default value for strings type data are set as an empty string.
Default value for booleans type data is FALSE.

 

PHP variable Scope

There are 3 different variable scope

  • local scope
  • global scope
  • static scope

Variables are accessible within only that function in which it is declared.
And this type of variables are called as local variables.
Any variable used inside a function is by default limited to the local function scope.

Local Scope

Example:

Global Scope

To declared variable as global, use the global keyword before the variables.
There is no limit to the number of global variables that can be manipulated by a function.

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.