In PHP Variables are used for storing values such as numeric values, characters, character strings, or memory addresses.
In PHP, a variable starts with the $ sign, followed by the name of the variable.
Rules for PHP variables:
<!DOCTYPE html>
<html>
<body>
<?php
$a = "www.studentstutorial.com";
echo " $a is a PHP Tutorial";
? >
</body>
</html>
www.studentstutorial.com is a PHP Tutorial
<!DOCTYPE html>
<html>
<body>
<?php
$a = 20;
$b= 10;
echo $a + $b;
? >
</body>
</html>
30
Note- Variable name are user defined. You can take any name as your choice.
PHP has three different variable scopes:
A variable declared within a function is called as LOCAL SCOPE and can only be accessed within that function.
<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
$a = 10; // local scope
echo "<p>Variable a inside function is: $a</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable a outside function is: $a</p>";
? >
</body>
</html>
A variable declared outside a function is called as GLOBAL SCOPE variable and can only be accessed outside a function:
<!DOCTYPE html>
<html>
<body>
<?php
$a = 10; // global scope
function myTest() {
// using a inside this function will generate an error
echo "<p>Variable a inside function is: $a</p>";
}
myTest();
echo "<p>Variable a outside function is: $a</p>";
? >
</html>
A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.