PHP Variables
A variable in PHP starts with a dollar sign ($), followed by the variable's name. PHP is a loosely typed language, so you do not need to declare the data type of a variable before using it โ PHP figures it out automatically based on the assigned value.
Variable names must start with a letter or underscore, can contain letters, numbers and underscores, and are case-sensitive. Variables can be reassigned to hold different values, even of different types, throughout a script.
$variableName = value;Declaring variables
You create a variable simply by assigning a value to it with the = operator, such as $name = "Amy";. There is no need for a separate declaration step.
Variable scope
A variable declared inside a function is local to that function by default. Variables declared outside any function have global scope and are accessible throughout the top-level script.
<?php
$name = "Amy";
$age = 25;
echo "$name is $age years old.";
?>Amy is 25 years old.Variables inside a double-quoted string are automatically replaced by their values.
<?php
$x = 5;
$x = "now text";
echo $x;
?>now textPHP variables can change type when reassigned, since PHP is loosely typed.
Key points
- PHP variables start with a $ sign.
- You do not need to declare a variable's type.
- Variable names are case-sensitive.
- Variables in double-quoted strings are automatically interpolated.
