PHP 5 Variables: Example 1
PHP 5 Variables: Example 1
Variables are "containers" for storing information. In PHP, a variable starts with the $ sign,
followed by the name of the variable:
Example 1:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
A variable starts with the $ sign, followed by the name of the variable
A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
Example 2:
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
Example 3:
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
Example 4:
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
local
global
static
A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function:
Example 6:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>