PHP Variables & Constants
Understanding PHP Variables
PHP variables are fundamental building blocks for storing and manipulating data in your scripts. Unlike many other programming languages, PHP variables are loosely typed, meaning you don't need to declare their type explicitly.
Variable Declaration and Naming Rules
To create a variable in PHP, you start with a dollar sign ($) followed by the variable name:
<?php
$username = "JohnDoe";
$age = 30;
$price = 19.99;
?>
Key rules for PHP variable names:
- Must start with a letter or underscore
- Can only contain letters, numbers, and underscores
- Are case-sensitive (
Name
≠name
) - Should follow consistent naming conventions (camelCase or snake_case)
PHP Constants: Immutable Values
Constants are identifiers for simple values that cannot change during script execution. They're particularly useful for configuration values that remain fixed.
Defining Constants
PHP offers two ways to define constants:
1. Using the define() function:
<?php
define("SITE_NAME", "My PHP Site");
define("MAX_USERS", 100);
// Example usage:
echo "Welcome to " . SITE_NAME . "<br>";
echo "Maximum allowed users: " . MAX_USERS;
?>
Output
Welcome to My PHP Site
Maximum allowed users: 100
Maximum allowed users: 100
Using the const keyword (only at compile-time):
<?php
// Database configuration constants
const DB_HOST = "localhost";
const DB_USER = "admin";
const DB_PASS = "secure123";
const DB_NAME = "my_database";
// Example usage in database connection
echo "Connecting to database...<br>";
echo "Host: " . DB_HOST . "<br>";
echo "Username: " . DB_USER . "<br>";
?>
Output
Connecting to database...
Host: localhost
Username: admin
Host: localhost
Username: admin
Key Differences Between Variables and Constants
- Mutability: Variables can be changed; constants cannot
-
Syntax: Variables use
$
prefix; constants don't - Scope: Constants are automatically global
- Case-sensitivity: Constants can be case-sensitive or insensitive
Best Practices for PHP Variables and Constants
Variable Best Practices
- Use descriptive names that indicate purpose
- Initialize variables before use
- Consider type safety with type hints (PHP 7+)
- Avoid global variables when possible
- Use proper scoping to prevent naming conflicts
Constant Best Practices
- Use uppercase names with underscores by convention
- Group related constants in classes or namespaces
- Consider using class constants for better organization
- Document constants with comments explaining their purpose