PHP Data Types and Variables — string, int, bool
PHP Variables
Variables are "containers" for storing information. A variable can be used to hold values (eg. x=5) and expression (eg. z=x+y). PHP has no command for declaring a variable. We have to assign value to the PHP variable, while the creation of variable. If we want to create variable without assigning a value to it, then we assign NULL value to it. Generally in PHP, a variable does not need to be declared before adding a value to it.
Standard Rules for PHP Variable Names
Scope of PHP Variables
Each variable has an area in which it exist, known as its scope PHP has four different variable scope:-
Local Scope:- A variable declared within a any PHP function is local and can only be accessed within that function.
<?php
$X=5 //Global
function myFun() {
echo $X //Local
}
myFun();
?>
The above script will not give any output, because the echo statement refers to the local scope.
- PHP is dynamically typed - variables automatically take the type of the value assigned.
- Use gettype() to check a variable's type and settype() to convert it.
- PHP has 8 primitive types: int, float, string, bool, array, object, null, and resource.
- Variable names start with $ and are case-sensitive - \ and \ are different variables.
- Use var_dump() for debugging - it shows both the type and value of a variable.
- Type juggling (automatic type conversion) can cause unexpected behavior - use strict comparison (===) to avoid it.
Level Up Your Php Skills
Master Php with these hand-picked resources