Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

PHP

Learn step by step



Variable in PHP

Variables are used for storing values, like text strings, numbers or arrays.
When a variable is declared, it can be used over and over again in your script.
All variables in PHP start with a $ sign symbol.
The correct way of declaring a variable in PHP:



<?php
$var_name = value;
?>

Let's try creating a variable containing a string, and a variable containing a number:



<?php
$txt="Hello World!";
$x=16;
?>
Naming Rules for Variables

A variable name must start with a letter or an underscore "_"
A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString)

PHP Variables Scope

In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
local
global
static

Local and Global Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
The following example tests variables with local and global scope:


<?php
$x=15; // global scope
function Test()
{
$y=100; // local scope
echo "<p> variables inside the function:</p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
echo "<p>Test variables outside the function:</p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>


Related Videos