Friday 25 November 2011

PHP Variable


  • Variable is a storage area where the values can be stored. These values may be a fixed value or the value which is inputted by the user.
  • Variable in PHP are represented by a doller ($) sign followed by the name of the variable.
  • The variable name is case-sensitive.

Syntax

                  $variable_name = value;

Example

<?php     
     $str = “Hello World”;
     $a=10;
echo $str.”<br/>”;
echo $a;
?>

There are some Rules for naming the variable which is required to follow them, are as below.

1.      The first letter of the variable-name should be alphabet.
2.      The variable-name can consist of digits or alphabet.
3.      There should be no space between the variable-name.
4.      No special symbol other than underscore (_) is used.
5.      Variable-name cannot be keyword.
6.     The length of variable-name maximum is 31 characters.

Ø       The global keyword

  • In php global variables must be declared global inside a function if they are going to be used in that function using global keyword.


Example

<?php 
          $a =10;
          function test()
          {
                   global $a;
                   echo $a;       //10
          }
          test();
?>

  • The above script will output 10. By declaring $a global within the function, all reference to either variable will refer to the global version.

Ø       The static keyword

  • Another important feature of variable scope is the static variable.
  • A static variable exits only in a local function scope, but it does not lose its value when program execution leaves this scope. consider  the following example.

Example

<?php 
          function test()
          {
                   static $a=1;
                   echo $a." ";
                   $a++;
          }
          test();
          test();
          ?>

Output

               1 2

  • Now, every time the test() function is called it will print the value of $a and increment it.
Posted By : Hemangi Zala

1 comment:

  1. Thanks for this explanation.Its very simple to understand.and just you can see the reference for PHP

    ReplyDelete