PHP Variables
In PHP, variables are used to store data that can be used and manipulated throughout a script. Here’s a quick guide to PHP variables:
1. Basic Syntax
-
All variables start with a dollar sign (
$
) followed by the variable name. -
Variable names are case-sensitive (
$name
and$Name
are different). -
A variable name must start with a letter or underscore, followed by letters, numbers, or underscores.
2. Variable Types
PHP is a loosely typed language, so you don’t have to declare data types. PHP automatically converts the variable to the correct data type.
Examples:
3. Variable Scope
-
Local: Declared inside a function and accessible only within that function.
-
Global: Declared outside all functions and accessible using the
global
keyword inside functions. -
Static: Preserves a variable's value after a function ends.
-
Superglobals: Built-in variables like
$_POST
,$_GET
,$_SERVER
.
Example of global:
4. Variable Variables
You can dynamically create variable names using variable variables: