Variables and Constants in PHP
Learn the fundamental concepts of Variables and Constants in PHP with this detailed guide. Understand their differences, characteristics, naming rules, and best practices to write efficient PHP code. Explore how variables store dynamic data, while constants hold fixed values throughout execution.
What is a Variable?
A variable in PHP is a container used to store data that can change during program execution. It is declared using the $ symbol, followed by an identifier name.
Characteristics of Variables in PHP:
- Start with
$symbol (e.g.,$name,$age). - Must begin with a letter or an underscore (_) but cannot start with a number.
- Case-sensitive (
$nameand$Nameare different). - Can store different data types (string, integer, float, boolean, array, object, etc.).
- Can be reassigned different values at any point in the script.
Declaring a Variable in PHP
A variable in PHP does not require an explicit data type declaration. The value assigned determines the type dynamically.
<?php
$name = "John"; // String
$age = 25; // Integer
$price = 99.99; // Float
$isActive = true; // Boolean
?>
Rules for Naming Variables:
✅ Valid Variable Names:
$studentName$_user_id$totalAmount
❌ Invalid Variable Names:
$1name❌ (Cannot start with a number)$my name❌ (Spaces are not allowed)$total-amount❌ (Hyphens are not allowed, use underscores_)
What is a Constant?
A constant is a fixed value that cannot be changed after its declaration. Constants are useful for storing values that remain the same throughout script execution, such as database credentials or configuration settings.
Characteristics of Constants in PHP:
- Defined using
define()orconstkeyword. - Do not use the
$symbol like variables. - Case-sensitive by default.
- Global scope – available throughout the script.
- Cannot be changed or undefined once set.
Declaring a Constant in PHP
1. Using define() function
<?php
define("SITE_NAME", "TECHSKILLGURU");
echo SITE_NAME;
define("MAX_USERS", 100);
echo MAX_USERS;
?>
2. Using const keyword (only inside classes and global scope)
<?php
const PI = 3.14159;
const API_KEY = "12345ABCDE";
?>
Rules for Naming Constants:
✅ Valid Constant Names:
SITE_NAMEMAX_USERSPI_VALUE
❌ Invalid Constant Names:
1VALUE❌ (Cannot start with a number)my constant❌ (Spaces are not allowed)site-name❌ (Hyphens are not allowed)
Differences Between Variables and Constants
| Feature | Variables | Constants |
|---|---|---|
| Symbol Used | Uses $ (e.g., $name) |
No $ symbol (e.g., SITE_NAME) |
| Value Change | Can be changed anytime | Cannot be modified after declaration |
| Scope | Local or global scope | Global scope by default |
| Definition Method | Assigned with = operator |
Declared using define() or const |
| Case Sensitivity | Case-sensitive ($name ≠ $Name) |
Case-sensitive by default |
| Memory Efficiency | Uses memory dynamically | Fixed memory allocation |
| Example | $age = 25; |
define("MAX_AGE", 100); |