PHP Variables
PHP Variables
1. Introduction
Variables in PHP are used to store data, such as numbers, text strings, arrays, and
objects, which can then be manipulated throughout a program. Understanding how
to declare, use, and manage variables is crucial for effective PHP programming.
In PHP, a variable is declared using a dollar sign ($) followed by the name of the
variable.
Syntax:
$variable_name = value;
variable_name: Must start with a letter (a–z, A–Z) or underscore (_) followed
by any number of letters, numbers, or underscores.
Example:
<?php
$name = "John";
$age = 25;
?>
4. Types of Variables
PHP is a loosely typed language, meaning you do not have to declare the data type of
a variable explicitly. PHP automatically converts the variable to the correct data type
based on its value.
Type Example
String $name = "Hello World";
Integer $age = 20;
Float/Double $price = 10.99;
Boolean $is_valid = true;
Array $colors = array("red", "green");
Object $car = new Car();
NULL $data = NULL;
Resource Special variables for external resources (like database connections)
Scope refers to the context within which a variable is defined and accessible.
a) Local Scope:
Variables declared inside a function are only accessible within that function.
<?php
function myFunction() {
$x = 10; // local scope
echo $x;
}
myFunction();
// echo $x; // This would produce an error
?>
b) Global Scope:
Variables declared outside of any function have a global scope and can be accessed
anywhere outside functions.
<?php
$x = 5; // global scope
function myTest() {
global $x;
echo $x;
}
myTest();
?>
c) Static Scope:
When a function is called, all its variables are normally deleted after execution. If you
want a local variable not to be deleted, use the static keyword.
<?php
function myCounter() {
static $count = 0;
echo $count;
$count++;
}
myCounter();
myCounter();
myCounter();
?>
6. Superglobals
PHP provides several built-in variables that are always accessible, regardless of
scope.
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
7. Variable Variables
Example:
<?php
$a = "hello";
$$a = "world";
9. Conclusion
Variables are an essential part of PHP programming. They enable developers to write
dynamic and flexible code by storing and manipulating data efficiently. By
understanding how to properly declare, use, and manage variables — along with
their scopes and types — programmers can build more robust and maintainable PHP
applications.
Mastering the handling of variables is the foundation for moving on to more complex
concepts such as functions, classes, and data management in PHP.