PHP 8 Variables
A variable is a name or symbol that contains a value. We assign a value to a variable and that variable becomes a reference to the assigned value
Declaring a variable
<?php
$a1 = 10;
$a2 = "Good Morning!";
?>
In the above example, $a1 and $a2 are variables. The variable $a1 holds the number value 10 and $a2 holds the string value 'Good Morning!'.
These are some useful features of PHP variables-
- It does not need to define a datatype of a variable before assigning them to a value.
- We cannot say the variable is used for which data type integer or string or boolean. So we can easily convert from one data type into another.
- In PHP, by default a variable has a null value.
- In PHP, a variable leads with a dollar ($) sign and then can be starts with a letter or underscore (_),
means first letter should be (A-Za-z) or (_), then you can use as many alphanumerics and characters.
These are valid variable examples in PHP.
$var
$var1
$_var
$_var23 - Using equal to (=) assignment operator, we can assign a value to a variable.
- PHP variable names are case sensitive.
- The value of a variable is the value of its most recent assignment.
<?php
$var = 23;
$var1 = 'Welcome to eTutorial';
$_var = 15.5;
?>
Scopes of PHP 8 variables
PHP variable has two scopes - Global and Local.
Global Scope -
PHP variable declares outside of a function has global scope. The value of the variable has remained same until it is not reassigned other value.
Local Scope -
PHP variable declares inside a function has local scope.
If a variable with the same name is declared inside and outside of the function, then both are considered as different.
Example -
<?php
$var = 100;
function demo() {
$var = 50;
echo $var;
}
demo();
echo '<br/>';
echo $var;
?>
In the above example, first value assign to $var has global scope wheras the value assign to $var within demo() function has
local scope.The output of the above example is -
50
100
Checking PHP variable assignment
PHP variables do not have to be assigned before use, in some situations you can actually convey information by selecting setting or not setting a variable. PHP provides a function called isset that tests a variable to see whether it has been assigned a value or not.
Example -$my_var = 'check assignment';
if(isset($my_var)) {
echo 'my_var is set';
} else {
echo 'my_var is not set';
}
Practice Exercises