Variables In PHP

admin_img Posted By Bajarangi soft , Posted On 03-10-2022

Variables are used to store data, like string of text, numbers, etc..

Types of variables in PHP

PHP Variables:

  • In PHP we can define a valriabel using $ sign .
  • After define variable name assingnment operator (=) define value of variable.
  • We do not need to declare the data types of the variables. It automatically analyzes the values and makes conversions to its correct datatype.
  • One time declared variable we can use multiple times in our code.

How to declare variable:

  • PHP variable must start with $ .
  • A variable name must start with letter(A to Z) or underscore(_).
  • Variable name can contain only letter,underscore and numeric value.
  • Keep in mind that a variable name does not start with special symbols or numbers. 
  • Variable name does not contain any space.
  • PHP variables are case sensetive.

Syntax of declaration variable:

$variable_name = value;

Example:

<?php
        // here we have some variables
      $var = PHP;
      $a = 7;
      $b = 5;
      echo "Welcome To $var";
      echo $a + $b;
?>

Output:

//return output will look like this
Welcome To PHP
12

Example:

<?php
        
     $name = "mike"; 
     // here we were concated two strings       
     echo "Hii everyone my name is" .$name. "!";
        
?>

Output:

//output will look like this
Hii everyone my name is mike !

Scopes Of Variables:

PHP has three different variable scopes:
  • global
  • local
  • static

1.Global Variable:

Global variables refer to any variable that is define outside of the function.and it can be accessed from any part of the script.

Example:

<?php
$val = 10;

     function add( ) {
     global $val;
     $val++;
     printr "My age is $val ";
}
add();

?>

Output:

//output will look like this
My age is 11

2.Local variable:

  •  The local variable exists until the block of the function is under execution. After that, it will be destroyed automatically.
  •  The local variable declare inside the function.

Example:

<?php

    function var( )
     {
        $value = 21;
        echo "Mike is " .$value. "old now. ";
     }
     var();

?>

Output:

//output will look like this
Mike is 21 old now.

3. Static Variable:

You can declare a variable to be static simply by placing the keyword STATIC in front of the variable name.

Example:

<?php
        function add() {
           STATIC $a= 0;
           $a++;
           print $a;
           print "<br />";
        }
        add();
        add();
        add();
?>

Output:

//output will look like this
1
2
3

Related Post