CodesJava

Easy learning with example program codes

PHP Variable


A variable is a temporary memory location that holds its data temporarily. PHP is said to be a loosely typed language, as it automatically corrects the data type of the variable, according on its value.

Syntax:

$variable_name=value; 

Rules for using PHP Variables:

  • PHP Variables starts with a $ sign followed by the variable name.
  • PHP Variable name starts with a letter or underscore only; numbers and special characters are restricted for this.
  • PHP Variables name can contain alphanumeric characters and underscores only.
  • PHP Variable names are case sensitive.
  • Putting a quote around the text value of the variables is necessary for the PHP Variables.
  • PHP Variables are created and declared once the value is assigned to them.

PHP Variables Scope:

PHP Variable Scope is used to specify the portion of the script where the variable can be used. These are:

  • Local: Local Variables can only be accessed within the function where it is declared.
  • Global: Global Variables can only be declared and accessed outside a function.
  • Static: The variables inside a function gets deleted, once the function execution ends. The Static Variables contains the last information even after the completion of the function.

 
Example 1: Declaring PHP Variable with a Local scope

<!DOCTYPE html>
<html>
<body>
 
<?php
Function example() {
    $v = 5; 
    echo "<p>Value of v is: $v</p>";
}
example();
 
echo "<p>Value of v is: $v</p>";
?>
 
</body>
</html>

Example 2: Declaring PHP Variable with a Global scope

<!DOCTYPE html>
<html>
<body>
 
<?php
$v = 5; 
 
Function example() {
     echo "<p>Value of v is: $v</p>";
}
example();
 
echo "<p>Value of v is: $v</p>";
?>
 
</body>
</html>

Example 3: Declaring Static PHP Variables

<!DOCTYPE html>
<html>
<body>
 
<?php
function example() {
    static $v = 3;
    echo $v;
    $v--;
}
 
example();
echo "<br>";
example();
echo "<br>";
example();
?>
 
</body>
</html>
Posted in PHP   
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki