Press "Enter" to skip to content

phpvariable

PHP Variable

PHP  variable is temporary area which hold the information in php script. 

 

How are variables declared and used in PHP?

In PHP $ sign is using in front of the variable name.
Some important points to know about variables:
PHP is a loosely typed language, so no need to declare the data types of the variables which is used in PHP code . It automatically analyzes the values and stores correct data type into the variable

Example for for PHP Variable

<?php
$n=10;
$m=20;
echo “Number :$n and $m”;
?>

PHP Variable Scope

Variable scope means where it is defined and how the script can access from the code. Or the context within which it is defined. In PHP the variable scope can be local and global

<?php
$ctr = 1;
include ‘test.php’;
?>

  • In the above example, ctr has used
  • this ctr variable also has  used in test.php
  • Variable used in user  define function is local

$x = 1;  /* global scope */ 

function w3html()

    echo $x; /* reference to local scope variable */ 

echo ” x variable has =”.$x;

w3html();
?>

  • $x is a global variable  
  • In function, $x has local scope 
  • The output of the above will display   “x variable has=” 
  • $x will be blank due to variable  scope

The Global keyword

  • In the above example $x variable not displaying any output due to the scope of the variable.
  • Define global keyword in front of $x ,which is used in w3html() function.

$x = 7;  /* global scope */ 

function w3html()

global $x;
    echo $x; /* reference to local scope variable */ 

echo ” x variable has =”.$x;

w3html();
?>

Naming Rules/Convention for Variables

• PHP variable name only start with a letter or an underscore “_”

• PHP variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )

• PHP variable name should not contain spaces. For more than one word should be separated by underscore ($w3_html), or with capitalization ($w3Html)

• PHP variable $n and $N both are different .In PHP variable name is case sensitive