#Variables and Constants
#Overview
Variables and constants are fundamental building blocks in PHP. This chapter covers variable declaration, scope, lifetime, superglobals, constants, and best practices for managing data in PHP applications.
#Variables
#Variable Basics
#Declaration and Assignment
<?php
// Variable declaration and assignment
$name = "John Doe";
$age = 30;
$salary = 50000.50;
$isActive = true;
// Multiple assignment
$a = $b = $c = 10;
// Reference assignment
$original = "Hello";
$reference = &$original;
$reference = "World";
echo $original; // "World" (changed due to reference)
?>#Variable Naming Rules
<?php
// Valid variable names
$userName = "john";
$user_name = "jane";
$_private = "hidden";
$user2 = "second user";
$HTML = "<h1>Title</h1>";
// Invalid variable names (will cause errors)
// $2user = "error"; // Cannot start with number
// $user-name = "error"; // Cannot contain hyphens
// $user name = "error"; // Cannot contain spaces
// $class = "error"; // Cannot use reserved words as variables
?>#Variable Variables
<?php
$var = "name";
$name = "John";
// Variable variable - uses value of $var as variable name
echo $$var; // Output: John (equivalent to $name)
// More complex example
$prefix = "user_";
$user_id = 123;
$user_name = "Alice";
$user_email = "alice@example.com";
$field = "id";
echo ${$prefix . $field}; // 123 (equivalent to $user_id)
$field = "name";
echo ${$prefix . $field}; // Alice (equivalent to $user_name)
// Dynamic property access
class User {
public $name = "John";
public $email = "john@example.com";
}
$user = new User();
$property = "name";
echo $user->$property; // "John"
?>#Variable Scope
#Global Scope
<?php
$globalVar = "I am global";
function testGlobal() {
// This won't work - $globalVar is not accessible here
// echo $globalVar; // Undefined variable error
// Use global keyword to access global variable
global $globalVar;
echo $globalVar; // "I am global"
// Modify global variable
$globalVar = "Modified globally";
}
testGlobal();
echo $globalVar; // "Modified globally"
// Alternative: Using $GLOBALS superglobal
function testGlobals() {
echo $GLOBALS['globalVar']; // "Modified globally"
$GLOBALS['globalVar'] = "Modified via GLOBALS";
}
testGlobals();
echo $globalVar; // "Modified via GLOBALS"
?>#Local Scope
<?php
function testLocal() {
$localVar = "I am local";
echo $localVar; // Works fine
// Local variable is destroyed when function ends
}
testLocal();
// echo $localVar; // Undefined variable error
// Function parameters are local
function greet($name) {
$message = "Hello, " . $name;
return $message;
}
echo greet("Alice"); // "Hello, Alice"
// echo $name; // Undefined variable error
// echo $message; // Undefined variable error
?>#Static Variables
<?php
function counter() {
static $count = 0; // Initialized only once
$count++;
echo "Count: $count\n";
}
counter(); // Count: 1
counter(); // Count: 2
counter(); // Count: 3
// Static variables in classes
class PageView {
public static $totalViews = 0;
public function __construct() {
self::$totalViews++;
}
public static function getTotalViews() {
return self::$totalViews;
}
}
$page1 = new PageView();
$page2 = new PageView();
echo PageView::getTotalViews(); // 2
?>#Superglobals
#$_GET and $_POST
<?php
// URL: http://example.com/page.php?name=John&age=30
echo $_GET['name']; // "John"
echo $_GET['age']; // "30"
// Safe access using null coalescing operator
$name = $_GET['name'] ?? 'Guest';
$age = $_GET['age'] ?? 0;
// POST data from forms
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
// Process form data
if (!empty($username) && !empty($password)) {
// Authenticate user
}
}
// Combined GET and POST data
$allInput = $_REQUEST; // Contains GET and POST (not recommended for security)
?>#$_SESSION
<?php
// Start session
session_start();
// Set session variables
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';
$_SESSION['is_logged_in'] = true;
// Access session variables
if (isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in']) {
echo "Welcome back, " . $_SESSION['username'];
} else {
echo "Please log in";
}
// Remove session variable
unset($_SESSION['temp_data']);
// Destroy entire session
// session_destroy();
?>#$_COOKIE
<?php
// Set cookie
setcookie('user_preference', 'dark_theme', time() + 3600); // Expires in 1 hour
// Access cookie
$theme = $_COOKIE['user_preference'] ?? 'light_theme';
// Set cookie with more options
setcookie('secure_cookie', 'value', [
'expires' => time() + 3600,
'path' => '/',
'domain' => '.example.com',
'secure' => true, // HTTPS only
'httponly' => true, // Not accessible via JavaScript
'samesite' => 'Strict'
]);
// Delete cookie
setcookie('user_preference', '', time() - 3600);
?>#$_SERVER
<?php
// Server and environment information
echo $_SERVER['HTTP_HOST']; // example.com
echo $_SERVER['REQUEST_URI']; // /path/to/page.php?query=value
echo $_SERVER['REQUEST_METHOD']; // GET, POST, etc.
echo $_SERVER['HTTP_USER_AGENT']; // Browser information
echo $_SERVER['REMOTE_ADDR']; // Client IP address
echo $_SERVER['SERVER_NAME']; // Server hostname
echo $_SERVER['DOCUMENT_ROOT']; // Web server document root
// Useful server variables
$isHTTPS = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
$currentURL = ($isHTTPS ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$userIP = $_SERVER['REMOTE_ADDR'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? 'unknown';
?>#$_FILES
<?php
// File upload handling
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload'])) {
$file = $_FILES['upload'];
// File information
echo "Name: " . $file['name']; // Original filename
echo "Type: " . $file['type']; // MIME type
echo "Size: " . $file['size']; // File size in bytes
echo "Temp: " . $file['tmp_name']; // Temporary file path
echo "Error: " . $file['error']; // Error code
// Check for upload errors
if ($file['error'] === UPLOAD_ERR_OK) {
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($file['name']);
if (move_uploaded_file($file['tmp_name'], $uploadFile)) {
echo "File uploaded successfully";
} else {
echo "Upload failed";
}
}
}
?>#$_ENV and $GLOBALS
<?php
// Environment variables
echo $_ENV['PATH'] ?? 'Path not set';
echo $_ENV['HOME'] ?? 'Home not set';
// Custom environment variables (from .env file or system)
$dbHost = $_ENV['DB_HOST'] ?? 'localhost';
$dbName = $_ENV['DB_NAME'] ?? 'myapp';
// $GLOBALS contains all global variables
$globalVar = "test";
function showGlobals() {
// Access any global variable
echo $GLOBALS['globalVar']; // "test"
// List all global variables
foreach ($GLOBALS as $key => $value) {
if (!is_array($value) && !is_object($value)) {
echo "$key: $value\n";
}
}
}
?>#Constants
#Defining Constants
#Using define()
<?php
// Basic constants
define('SITE_NAME', 'My Website');
define('VERSION', '1.0.0');
define('MAX_USERS', 1000);
define('PI', 3.14159);
define('DEBUG', true);
// Case-insensitive constants (deprecated in PHP 7.3)
define('GREETING', 'Hello', true);
echo greeting; // Works but not recommended
// Array constants (PHP 7.0+)
define('FRUITS', ['apple', 'banana', 'orange']);
echo FRUITS[0]; // "apple"
// Constants with expressions (PHP 5.6+)
define('TIMESTAMP', time());
define('RANDOM_ID', 'ID_' . uniqid());
?>#Using const Keyword
<?php
// Class constants
class MathConstants {
const PI = 3.14159;
const E = 2.71828;
const GOLDEN_RATIO = 1.618;
// Constant expressions (PHP 5.6+)
const TWO_PI = self::PI * 2;
// Visibility modifiers (PHP 7.1+)
private const SECRET = 'hidden';
protected const INTERNAL = 'protected';
public const PUBLIC = 'visible';
}
// Namespace constants
namespace MyApp;
const APP_NAME = 'My Application';
const VERSION = '2.0.0';
// Accessing constants
echo MathConstants::PI; // 3.14159
echo MathConstants::TWO_PI; // 6.28318
echo \MyApp\APP_NAME; // "My Application"
?>#Magic Constants
<?php
// Magic constants change based on context
echo __LINE__; // Current line number
echo __FILE__; // Full path of current file
echo __DIR__; // Directory of current file
echo __FUNCTION__; // Current function name
echo __CLASS__; // Current class name
echo __TRAIT__; // Current trait name
echo __METHOD__; // Current method name
echo __NAMESPACE__; // Current namespace
// Practical examples
function debugInfo() {
echo "Function: " . __FUNCTION__ . "\n";
echo "File: " . __FILE__ . "\n";
echo "Line: " . __LINE__ . "\n";
}
class Logger {
public function log($message) {
$timestamp = date('Y-m-d H:i:s');
$class = __CLASS__;
$method = __METHOD__;
echo "[$timestamp] $class::$method - $message\n";
}
}
// Include path helper
require_once __DIR__ . '/config/database.php';
?>#Predefined Constants
<?php
// PHP version constants
echo PHP_VERSION; // PHP version string
echo PHP_MAJOR_VERSION; // Major version number
echo PHP_MINOR_VERSION; // Minor version number
// System constants
echo PHP_OS; // Operating system
echo PHP_OS_FAMILY; // OS family (Windows, Linux, etc.)
echo DIRECTORY_SEPARATOR; // / or \ depending on OS
echo PATH_SEPARATOR; // : or ; depending on OS
// Math constants
echo M_PI; // Pi
echo M_E; // Euler's number
echo M_LOG2E; // Log base 2 of E
// File constants
echo FILE_APPEND; // Flag for file_put_contents()
echo LOCK_EX; // Exclusive lock flag
// Error constants
echo E_ERROR; // Fatal error
echo E_WARNING; // Warning
echo E_NOTICE; // Notice
// Boolean constants
echo TRUE; // 1
echo FALSE; // (empty)
echo NULL; // (empty)
?>#Constant Arrays and Objects
<?php
// Array constants (PHP 7.0+)
const COLORS = ['red', 'green', 'blue'];
const CONFIG = [
'database' => [
'host' => 'localhost',
'name' => 'myapp'
],
'cache' => [
'driver' => 'redis',
'ttl' => 3600
]
];
echo COLORS[1]; // "green"
echo CONFIG['database']['host']; // "localhost"
// Class constant arrays
class AppConfig {
const SUPPORTED_LANGUAGES = ['en', 'es', 'fr', 'de'];
const DEFAULT_SETTINGS = [
'theme' => 'light',
'language' => 'en',
'timezone' => 'UTC'
];
public static function getSetting($key) {
return self::DEFAULT_SETTINGS[$key] ?? null;
}
}
echo AppConfig::SUPPORTED_LANGUAGES[0]; // "en"
echo AppConfig::getSetting('theme'); // "light"
?>#Variable and Constant Best Practices
#Naming Conventions
<?php
// Variables: camelCase or snake_case
$userName = "john_doe"; // camelCase (recommended)
$user_name = "jane_doe"; // snake_case (also acceptable)
$isLoggedIn = true;
$has_permission = false;
// Constants: UPPER_SNAKE_CASE
const MAX_LOGIN_ATTEMPTS = 3;
const API_BASE_URL = 'https://api.example.com';
const DEFAULT_TIMEOUT = 30;
// Class constants: UPPER_CASE
class UserRole {
const ADMIN = 'admin';
const MODERATOR = 'moderator';
const USER = 'user';
const GUEST = 'guest';
}
// Private/protected variables: underscore prefix (optional)
class MyClass {
private $_privateVar;
protected $_protectedVar;
public $publicVar;
}
?>#Variable Initialization
<?php
// Always initialize variables
$counter = 0;
$message = '';
$users = [];
$config = null;
// Use null coalescing for optional values
$page = $_GET['page'] ?? 1;
$limit = $_GET['limit'] ?? 10;
$sort = $_GET['sort'] ?? 'name';
// Proper array initialization
$errors = [];
$data = [
'users' => [],
'total' => 0,
'page' => 1
];
// Use appropriate default values
function processUser($id, $options = []) {
$defaultOptions = [
'validate' => true,
'cache' => false,
'timeout' => 30
];
$options = array_merge($defaultOptions, $options);
// Process user with options
}
?>#Constant Organization
<?php
// Group related constants
class DatabaseConfig {
const HOST = 'localhost';
const PORT = 3306;
const NAME = 'myapp';
const CHARSET = 'utf8mb4';
}
class CacheConfig {
const DRIVER = 'redis';
const TTL = 3600;
const PREFIX = 'myapp:';
}
// Use enums for related constants (PHP 8.1+)
enum Status: string {
case PENDING = 'pending';
case APPROVED = 'approved';
case REJECTED = 'rejected';
}
// Configuration class
class Config {
const ENVIRONMENTS = ['development', 'testing', 'production'];
private static $config = [];
public static function set($key, $value) {
self::$config[$key] = $value;
}
public static function get($key, $default = null) {
return self::$config[$key] ?? $default;
}
}
?>#Security Considerations
<?php
// Sanitize user input
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT);
// Escape output
$safeOutput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
// Use prepared statements for database queries
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
// Don't expose sensitive information in constants
// Bad: const DB_PASSWORD = 'secret123';
// Good: Use environment variables
$dbPassword = $_ENV['DB_PASSWORD'] ?? '';
// Validate and sanitize superglobal access
function getQueryParam($key, $default = null, $filter = FILTER_SANITIZE_STRING) {
return filter_input(INPUT_GET, $key, $filter) ?? $default;
}
$page = getQueryParam('page', 1, FILTER_VALIDATE_INT);
$search = getQueryParam('search', '', FILTER_SANITIZE_STRING);
?>#Memory Management
<?php
// Free large variables when done
$largeArray = range(1, 1000000);
// ... use array
unset($largeArray); // Free memory
// Use references for large data structures
function processLargeArray(&$array) {
// Process array without copying
foreach ($array as &$item) {
$item = strtoupper($item);
}
}
// Be careful with circular references
class ParentClass {
public $children = [];
}
class Child {
public $parent;
}
$parent = new ParentClass();
$child = new Child();
$parent->children[] = $child;
$child->parent = $parent;
// Break circular reference
unset($child->parent);
unset($parent->children);
?>#Advanced Variable Techniques
#Variable Functions
<?php
// Variable functions
$functionName = 'strlen';
echo $functionName('Hello'); // 5 (calls strlen('Hello'))
$mathOp = 'max';
echo $mathOp(1, 5, 3); // 5 (calls max(1, 5, 3))
// Dynamic method calls
class Calculator {
public function add($a, $b) {
return $a + $b;
}
public function multiply($a, $b) {
return $a * $b;
}
}
$calc = new Calculator();
$method = 'add';
echo $calc->$method(5, 3); // 8
// Callback array
$callback = [$calc, 'multiply'];
echo call_user_func($callback, 4, 5); // 20
?>#Extract and Compact
<?php
// Extract variables from array
$data = [
'name' => 'John',
'age' => 30,
'city' => 'New York'
];
extract($data);
echo $name; // "John"
echo $age; // 30
echo $city; // "New York"
// Compact variables into array
$username = 'alice';
$email = 'alice@example.com';
$active = true;
$user = compact('username', 'email', 'active');
// $user = ['username' => 'alice', 'email' => 'alice@example.com', 'active' => true]
// Safe extract with prefix
extract($data, EXTR_PREFIX_ALL, 'user');
echo $user_name; // "John"
echo $user_age; // 30
?>#Next Steps
Now that you understand variables and constants, let's explore PHP's operators in Operators.
#Practice Exercises
- Create a configuration system using constants and static variables
- Build a session management class using superglobals
- Implement variable validation and sanitization functions
- Practice variable scope with nested functions and classes
- Create a debugging utility that uses magic constants
Understanding variables and constants is essential for managing data effectively in PHP applications!