Variables are "containers" for storing information. In PHP, a variable starts with the $ sign, followed by the name of the variable.
Unlike many other languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
To write valid PHP, your variable names must follow these specific rules:
$ sign.$age and
$AGE are different).Scope refers to the part of the script where a variable can be referenced/used. PHP has three different variable scopes:
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
<?php
function myTest() {
$y = 5; // local scope
echo "<p>Variable y inside function is: $y</p>";
}
myTest();
// using y outside the function will generate an error
echo "<p>Variable y outside function is: $y</p>";
?>
The global keyword is used to access a global variable from within a
function. To do this, use the global keyword before the variables (inside
the function):
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
static keyword when you first declare the variable.
$userEmail instead of
$e).