PHP Reference
Free reference guide: PHP Reference
About PHP Reference
The PHP Reference is a comprehensive cheat sheet for PHP developers, with particular emphasis on PHP 8.0 and 8.1 features. It covers six categories: core language syntax (variables, control flow, match expressions, null coalescing `??`, nullsafe operator `?->`, enums), array manipulation functions (array_map, array_filter, array_reduce, array_merge, array_slice), string functions (strlen vs mb_strlen for multibyte, str_contains/str_starts_with, explode/implode, preg_match/preg_replace, sprintf), object-oriented PHP (classes with constructor promotion, interfaces, traits, abstract classes, readonly properties), file I/O (file_get_contents, fopen/fread, json_encode/json_decode, file_exists), and PDO database access (connection, prepared statements, transactions).
This reference is useful for web developers building PHP applications with frameworks like Laravel or Symfony, developers learning modern PHP 8 features after years of PHP 5/7 experience, and anyone who needs to quickly recall the difference between `array_map` and `array_walk`, or how to write a PDO prepared statement with named parameters. All examples are practical and directly usable in real applications.
The PHP reference is organized to reflect how PHP code is actually written: start with basic syntax and control structures, work through array and string transformations, define classes and interfaces using PHP 8 features like constructor property promotion and readonly properties, interact with the filesystem, and connect to a database using PDO with proper error handling and transaction support.
Key Features
- PHP 8 basics: variables, match expression, for/foreach/while loops, and constants
- Null coalescing operator (??) for safe default values and nullsafe operator (?->) for chained calls
- PHP 8.1 enums with backed cases (string/int) and value access
- Array functions: array_map, array_filter, array_reduce, array_merge, array_slice
- String functions: mb_strlen for Unicode, str_contains/str_starts_with (PHP 8+), preg_match/preg_replace
- OOP: constructor property promotion, interface/implements, traits, abstract classes, readonly properties
- File I/O: file_get_contents/file_put_contents, fopen/fgets streaming, json_encode/json_decode
- PDO: database connection, prepared statements with named parameters, lastInsertId, transactions with rollback
Frequently Asked Questions
What is constructor property promotion in PHP 8?
Constructor property promotion is a PHP 8 shorthand that lets you declare and initialize class properties directly in the constructor signature. Instead of declaring `private string $name;` as a property and then assigning `$this->name = $name` in the constructor body, you write `public function __construct(private string $name, private int $age) {}`. The visibility modifier (`public`, `protected`, or `private`) in the parameter list triggers automatic property creation and assignment.
What is the difference between the ?? and ?-> operators in PHP 8?
The null coalescing operator `??` returns the left operand if it is not null, otherwise returns the right operand. It is useful for providing default values: `$name = $_GET["name"] ?? "Guest"`. The nullsafe operator `?->` short-circuits method and property access on a null value, returning null instead of throwing an error: `$city = $user?->getAddress()?->getCity()` returns null if `$user` or `getAddress()` is null.
How do PHP enums (PHP 8.1) work?
PHP 8.1 enums define a closed set of named values. "Backed" enums associate a string or integer value with each case: `enum Status: string { case Active = "active"; case Inactive = "inactive"; }`. Access the backing value with `->value`: `Status::Active->value` returns `"active"`. You can also convert from a value with `Status::from("active")` (throws on invalid) or `Status::tryFrom("invalid")` (returns null).
What is the difference between array_map and array_filter in PHP?
`array_map(callback, $array)` applies a function to every element and returns a new array of the transformed values — it always returns an array of the same length. `array_filter($array, callback)` keeps only the elements for which the callback returns true — the result may be shorter. Note that `array_filter` preserves keys; use `array_values()` afterwards if you need sequential integer keys.
How do PHP traits differ from abstract classes and interfaces?
An interface defines a contract (method signatures only) that a class must implement. An abstract class can contain both abstract methods (no body) and concrete methods with implementations, but a class can only extend one abstract class. A trait is a mechanism for horizontal code reuse — it contains method implementations that are "mixed in" to a class with `use Timestamps;`. A class can use multiple traits but only extend one parent class.
How do I prevent SQL injection in PHP with PDO?
Always use prepared statements with bound parameters. Use named parameters like `":id"` or positional `"?"` placeholders in the SQL string, then pass the actual values to `$stmt->execute(["id" => $userId])` or `$stmt->execute([$userId])`. Never concatenate user input directly into SQL strings. PDO prepared statements ensure the database driver handles escaping correctly regardless of the input value.
What is the difference between file_get_contents and fopen in PHP?
`file_get_contents()` reads an entire file into a string in one call — simple and sufficient for small to medium files. `fopen()` with `fgets()` or `fread()` opens a file handle for streaming, allowing you to process the file line by line without loading it all into memory. Use `fopen()` for large log files or CSV files where memory usage matters. Both functions support the `FILE_APPEND` flag for appending.
How do PDO transactions work in PHP?
Begin a transaction with `$pdo->beginTransaction()`. Execute your queries inside a try-catch block. On success, call `$pdo->commit()`. If an exception is thrown, call `$pdo->rollBack()` in the catch block to undo all changes made since `beginTransaction()`. This guarantees atomicity — either all queries in the transaction succeed or none of them are applied. Set `PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION` when connecting to ensure query errors throw exceptions.