PHP Variables

PHP basic variables:

PHP variable is an identifier. It will start with a dollar sign ($). No need to declare any variable before using, like other any programming languages.

Example

variable variables:

It refers the value of another variable as the variable name.

Example

Now

$$tutorial is equal to $php

So $php outputs programming language

Variable scope:

The scope of the variable depends on the variable’s declaration. Depending on the place of declaration in the PHP programming we can access the variable.

There are four type of variable scope available in PHP, they are:

  • local
  • global
  • static
  • function parameters

Local:

The variable declared inside the function is called as local variable. It is accessible within the function only and it will not be known outside the function.

Example

Global:

Variable declared outside the function is called a global variable. It is accessible anywhere in the program.

Example

Static:

Static variable is an important feature in variable scoping. The static variable will maintain the state between every function calls and will not lose it’s latest value. PHP has two types of static functionality:

  • static in class variables and methods
  • static in functions

Consider the following example to understand static variable scope in class.

Example

Consider the following example to understand static variable scope in functions.

Example

Function parameters:

Function parameters are local to that function itself where it is passed to. They are available only inside their function.

Example

In the above example, $site_name is not accessible from outside callme() function.

Difference between global and static variable:

Global variable can be accessed anywhere in programming, whereas static variable is accessible only within the function scope.

Variable References:

One variable name referred by another variable name, is called a variable reference.

Consider the below example:

After assigning $black to $color, the $color will become ‘black’

Now change the value of $black

In this case, changing the value of $black will not affect the variable $color.

But instead of assigning {$color = $black;} if we assign {$color = & $black;}, then in the above case $black will affect the variable $color:

Example of assign by value:

Example of assign by reference:

Please follow and like us:

2 thoughts on “PHP Variables

Leave a Reply

Your email address will not be published. Required fields are marked *