PHP Handbook
PHP runs server-side web applications and command-line scripts. This handbook uses PHP 8.4 or later.
When to choose PHP
Choose PHP for a site that extends WordPress or an application that needs the routing, templates, and database tools of Laravel or Symfony. PHP hosting commonly supports the request-response model through a web server and PHP-FPM.
When to reconsider PHP
For a service that holds many connections open or keeps state in memory, evaluate a long-running worker model. With conventional PHP-FPM deployment, request-local application state is rebuilt for each request.
PHP and related alternatives
PHP can render HTML on the server and reuse its CMS ecosystem. Node.js lets a team use JavaScript or TypeScript on both sides of the web app. Python can share an application stack with data processing libraries. Compare the libraries you need and the runtime your team can operate.
Run your first PHP script
Install the PHP CLI using the installation guide below and run php -v to check that it is on your PATH. Save the example as example.php and run php example.php in the same directory.
<?php
echo "Hello, PHP", PHP_EOL;PHP executes top-level statements in order. The script prints Hello, PHP followed by a newline. Use the same filename and command for each PHP example below, replacing the file contents each time.
Resources
Topics
Variables and constants
Update a counter
Use a variable for a value that changes during a calculation.
<?php
$count = 2;
$count += 3;
echo $count, PHP_EOL;The assignment starts the counter at 2. Adding 3 updates it to 5.
Name a fixed value
Give a business rule a name with a constant.
<?php
const SECONDS_PER_MINUTE = 60;
echo 2 * SECONDS_PER_MINUTE, PHP_EOL;The expression prints 120. The constant can be read anywhere in this file after its declaration.
Strings and Unicode
Interpolate a product name
Use double quotes to insert a variable into a display string.
<?php
$product = 'Tea';
echo "{$product}-stock", PHP_EOL;Braces mark where the variable name ends, so the line reads Tea-stock.
Count bytes and characters
Save the file as UTF-8 and enable the mbstring extension before counting characters in text.
<?php
$label = 'café';
echo strlen($label), PHP_EOL;
echo mb_strlen($label, 'UTF-8'), PHP_EOL;The script prints 5 then 4. The accented letter occupies two bytes and counts as one Unicode code point.
Values and control flow
Compare numeric input
Convert text at the boundary before comparing it with a number.
<?php
$quantity = (int) '3';
if ($quantity === 3) {
echo "Three items\n";
}The cast produces an integer. Strict equality checks both type and value, so the branch prints Three items.
Map a status with match
Use match when each supported value maps to one result.
<?php
$status = 404;
echo match ($status) {
200 => 'OK',
404 => 'Missing',
default => 'Unknown',
}, PHP_EOL;The integer 404 selects Missing. Match uses strict comparisons and returns a value.
Functions and types
Declare a typed function
Give a calculation a name and declare the types of its inputs and result.
<?php
declare(strict_types=1);
function total(int $price, int $quantity): int
{
return $price * $quantity;
}
echo total(5, 3), PHP_EOL;The call prints 15. With strict types in the calling file, passing the string "5" to this integer parameter raises TypeError.
Handle an optional argument
Use a nullable parameter when callers can omit a name.
<?php
function greet(?string $name = null): string
{
return 'Hello, ' . ($name ?? 'guest');
}
echo greet(), PHP_EOL;
echo greet('Ada'), PHP_EOL;The default is null. The coalescing operator supplies guest for null, so the calls print Hello, guest and Hello, Ada.
Union types
Accept two input types
Use a union when a reference may arrive as an integer or a string.
<?php
declare(strict_types=1);
function label(int|string $id): string
{
return 'REF-' . $id;
}
echo label(7), PHP_EOL;
echo label('7'), PHP_EOL;Both calls print REF-7. Concatenation converts the integer to text, and the declared return type is string.
Reject values outside the union
Use strict types when callers must pass one of the declared scalar types.
<?php
declare(strict_types=1);
function identify(int|string $id): string
{
return (string) $id;
}
try {
identify(7.5);
} catch (TypeError $error) {
echo "Unsupported ID type\n";
}The caller passes a float, so PHP raises TypeError before entering the function. The catch block prints Unsupported ID type.
Closures and arrow functions
Capture a value in an arrow function
Use an arrow function for a short calculation that uses a variable from its surrounding scope.
<?php
$fee = 2;
$addFee = fn (int $price): int => $price + $fee;
$fee = 5;
echo $addFee(10), PHP_EOL;The arrow function captures the original fee by value. It prints 12 even though the outer fee has changed.
Share a counter by reference
Capture by reference when a callback must update a variable in the surrounding scope.
<?php
$count = 0;
$increment = function () use (&$count): void {
$count++;
};
$increment();
$increment();
echo $count, PHP_EOL;The closure updates the same counter on each call. After two calls the outer counter prints 2.
Lists and associative arrays
Accumulate a list
Use an array with consecutive integer keys to store an ordered list of quantities.
<?php
$quantities = [2, 4, 3];
$total = 0;
foreach ($quantities as $quantity) {
$total += $quantity;
}
echo $total, PHP_EOL;Foreach visits the values in order. The accumulator goes from 0 to 2, 6, and finally 9.
Look up a named key
Use string keys to look up values by name and supply a fallback for a missing key.
<?php
$stock = ['tea' => 4, 'coffee' => 2];
echo $stock['tea'], PHP_EOL;
echo $stock['water'] ?? 0, PHP_EOL;The first lookup prints 4. The second prints 0 because water is absent. The fallback also applies to an explicitly null value.
Array transformations
Transform every item
Use array_map to apply the same calculation to every element.
<?php
$quantities = [2, 4, 6];
$doubled = array_map(fn (int $quantity): int => $quantity * 2, $quantities);
echo implode(', ', $doubled), PHP_EOL;The callback doubles each quantity. The new array contains 4, 8, and 12, and the joined output is 4, 8, 12.
Filter and rebuild list indexes
Use array_filter to retain selected values, then array_values if the result needs consecutive list indexes.
<?php
$even = array_filter([2, 3, 4], fn (int $number): bool => $number % 2 === 0);
echo json_encode(array_values($even), JSON_THROW_ON_ERROR), PHP_EOL;Filtering preserves keys 0 and 2. Reindexing assigns keys 0 and 1, so JSON encoding prints the list [2,4].
Sorting arrays
Sort a list of prices
Use sort when the values should be ordered and the list can be updated in place.
<?php
$prices = [10, 3, 2];
sort($prices, SORT_NUMERIC);
echo implode(', ', $prices), PHP_EOL;The numeric comparison puts 2 before 10. The original variable now contains the sorted list and prints 2, 3, 10.
Preserve names while sorting
Use asort when values determine the order and the original keys must remain attached.
<?php
$menu = ['coffee' => 5, 'tea' => 3];
asort($menu, SORT_NUMERIC);
echo implode(', ', array_keys($menu)), PHP_EOL;Tea moves before coffee while both names stay attached to their prices. The script prints tea, coffee.
Classes and enums
Initialize a readonly property
Use a promoted constructor parameter to store the label on each object.
<?php
final class Product
{
public function __construct(public readonly string $name)
{
}
}
echo (new Product('Tea'))->name, PHP_EOL;The constructor initializes the property and the script prints Tea. Assigning a new string to name after initialization raises Error.
Convert input to an enum
Use a backed enum when external strings must map to a fixed set of domain values.
<?php
enum State: string
{
case Open = 'open';
case Closed = 'closed';
}
echo State::tryFrom('open')?->name ?? 'Unknown', PHP_EOL;
echo State::tryFrom('pending')?->name ?? 'Unknown', PHP_EOL;The first lookup returns State::Open and prints Open. The second returns null, so the nullsafe property access and coalescing operator produce Unknown.
Interfaces
Call through a contract
Type a function against an interface when it only needs one capability.
<?php
interface NamedItem
{
public function name(): string;
}
final class Tea implements NamedItem
{
public function name(): string
{
return 'Tea';
}
}
function announce(NamedItem $item): void
{
echo 'Ready ' . $item->name(), PHP_EOL;
}
announce(new Tea());The function calls name on the supplied object and prints Ready Tea.
Combine implemented contracts
Require two capabilities on the same argument with an intersection type.
<?php
interface Labeled
{
public function label(): string;
}
interface Priced
{
public function price(): int;
}
final class MenuItem implements Labeled, Priced
{
public function label(): string
{
return 'Tea';
}
public function price(): int
{
return 3;
}
}
function describe(Labeled&Priced $item): void
{
echo $item->label() . ' costs ' . $item->price(), PHP_EOL;
}
describe(new MenuItem());The object implements both interfaces, so describe can use both methods and prints Tea costs 3.
Inheritance and composition
Specialize inherited behavior
Override a method when a subclass needs a different implementation of the same operation.
<?php
class Shipping
{
public function cost(): int
{
return 5;
}
}
final class ExpressShipping extends Shipping
{
public function cost(): int
{
return 10;
}
}
echo (new ExpressShipping())->cost(), PHP_EOL;PHP dispatches the call to ExpressShipping, and the script prints 10.
Delegate to a collaborator
Use composition when an object needs another object's behavior as one part of its job.
<?php
final class Formatter
{
public function amount(int $dollars): string
{
return 'USD ' . $dollars;
}
}
final class Receipt
{
public function __construct(private Formatter $formatter, private int $amount)
{
}
public function total(): string
{
return $this->formatter->amount($this->amount);
}
}
echo (new Receipt(new Formatter(), 5))->total(), PHP_EOL;Receipt delegates formatting to the supplied formatter. It prints USD 5 while the receipt retains responsibility for its own amount.
Traits
Reuse a method in a class
Use a trait for a method implementation that multiple classes can share.
<?php
trait MakesSlug
{
public function slug(string $title): string
{
return str_replace(' ', '-', strtolower($title));
}
}
final class Article
{
use MakesSlug;
}
echo (new Article())->slug('Fresh Tea'), PHP_EOL;The use declaration makes slug available on Article. It lowercases the input and replaces spaces, producing fresh-tea.
Resolve overlapping trait methods
When two traits supply the same method, pick one and optionally expose the other under an alias.
<?php
trait ShortLabel
{
public function label(): string
{
return 'short';
}
}
trait LongLabel
{
public function label(): string
{
return 'long';
}
}
final class Badge
{
use ShortLabel, LongLabel {
ShortLabel::label insteadof LongLabel;
LongLabel::label as longLabel;
}
}
$badge = new Badge();
echo $badge->label(), PHP_EOL;
echo $badge->longLabel(), PHP_EOL;The original label call returns short. The alias still reaches the second implementation and returns long.
Property hooks
Compute a virtual property
Use a PHP 8.4 get hook when a property should reflect other state on each read.
<?php
final class Line
{
public function __construct(public int $price, public int $quantity)
{
}
public int $total {
get => $this->price * $this->quantity;
}
}
echo (new Line(4, 3))->total, PHP_EOL;Reading total runs the expression and prints 12. The object stores the price and quantity, and computes total on demand.
Normalize a stored property
Use a set hook when assignments should normalize the value before storing it.
<?php
final class Category
{
public string $name {
set {
$this->name = trim($value);
}
}
}
$category = new Category();
$category->name = ' Tea ';
echo $category->name, PHP_EOL;The set hook stores the trimmed value in the backing property. Reading it prints Tea with the surrounding spaces removed.
Namespaces
Declare a namespace
Put related declarations under a namespace to give them distinct fully qualified names.
<?php
namespace Shop\Inventory;
final class Stock
{
}
echo Stock::class, PHP_EOL;The class constant prints Shop\Inventory\Stock. PHP includes the namespace in the class name.
Import a class with an alias
Use an import alias when a fully qualified name is verbose or conflicts with a local name.
<?php
namespace Shop\Reporting;
use DateTimeImmutable as Clock;
$date = new Clock('2025-01-01T00:00:00+00:00');
echo $date->format('Y'), PHP_EOL;Clock resolves to the global DateTimeImmutable class and the formatted year is 2025.
Attributes and reflection
Read class metadata
Use an attribute to attach structured metadata to a class.
<?php
#[Attribute(Attribute::TARGET_CLASS)]
final class Section
{
public function __construct(public string $name)
{
}
}
#[Section('inventory')]
final class Report
{
}
$attributes = (new ReflectionClass(Report::class))->getAttributes(Section::class);
echo $attributes[0]->newInstance()->name, PHP_EOL;Reflection locates the Section attribute. Calling newInstance creates it with the configured value and the script prints inventory.
Inspect a return declaration
Use reflection when a tool needs to inspect a declared signature at runtime.
<?php
final class Inventory
{
public function count(): int
{
return 4;
}
}
$method = new ReflectionMethod(Inventory::class, 'count');
echo $method->getReturnType(), PHP_EOL;The reflection object reads the declaration without calling the method. The script prints int.
Files, JSON, and exceptions
Read structured data from disk
Create inventory.json beside the script with the contents shown here before reading it.
<?php
// inventory.json contains {"tea":4}
$path = __DIR__ . '/inventory.json';
$json = file_get_contents($path);
if ($json === false) {
throw new RuntimeException('Could not read inventory');
}
$stock = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
echo $stock['tea'], PHP_EOL;The file is resolved relative to the script. A read failure returns false and normally emits a warning. For the supplied file, decoding produces an associative array and the lookup prints 4.
Catch malformed JSON
Handle a decoding error where the program can choose how to report it.
<?php
try {
json_decode('{"tea":}', true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $error) {
echo "Invalid inventory JSON\n";
}The missing value after the colon causes JsonException. The catch block prints Invalid inventory JSON.
Generators
Yield values on demand
Use yield to produce a series incrementally as a consumer requests values.
<?php
function numbers(int $max): Generator
{
for ($number = 1; $number <= $max; $number++) {
yield $number;
}
}
foreach (numbers(3) as $number) {
echo $number, PHP_EOL;
}The generator resumes after each yield. The loop prints 1, then 2, then 3 on separate lines.
Delegate part of a sequence
Use yield from to pass through values from another iterable.
<?php
function drinks(): Generator
{
yield 'tea';
yield from ['coffee', 'water'];
}
foreach (drinks() as $drink) {
echo $drink, PHP_EOL;
}The loop consumes the starter first, then the two delegated values. It prints tea, coffee, and water on separate lines.
Dates and time zones
Add a calendar interval
Use DateTimeImmutable to derive a deadline while keeping the original date for reference.
<?php
$start = new DateTimeImmutable('2025-01-30T00:00:00+00:00');
$deadline = $start->add(new DateInterval('P3D'));
echo $start->format('Y-m-d'), PHP_EOL;
echo $deadline->format('Y-m-d'), PHP_EOL;Adding P3D creates a new date three calendar days later. The output shows 2025-01-30 followed by 2025-02-02.
Display an instant in another zone
Store an unambiguous instant and choose a time zone for display.
<?php
$instant = new DateTimeImmutable('2025-01-01T17:00:00+00:00');
$tokyo = $instant->setTimezone(new DateTimeZone('Asia/Tokyo'));
echo $tokyo->format('Y-m-d H:i T'), PHP_EOL;Converting to Tokyo preserves the instant and advances the displayed clock by nine hours. The output is 2025-01-02 02:00 JST.
Databases with PDO
Bind and retrieve a value
Enable PDO SQLite and use a prepared statement to bind a value to a SQL placeholder.
<?php
$db = new PDO('sqlite::memory:');
$db->exec('CREATE TABLE customer (name TEXT NOT NULL)');
$insert = $db->prepare('INSERT INTO customer (name) VALUES (:name)');
$insert->execute(['name' => "O'Neil"]);
echo $db->query('SELECT name FROM customer')->fetchColumn(), PHP_EOL;The name is passed as data, including the apostrophe. Reading the first column prints O'Neil.
Roll back a transaction
With PDO SQLite enabled, use a transaction when changes should be kept only after all related operations succeed.
<?php
$db = new PDO('sqlite::memory:');
$db->exec('CREATE TABLE inventory (quantity INTEGER NOT NULL)');
$db->beginTransaction();
$db->exec('INSERT INTO inventory (quantity) VALUES (3)');
$db->rollBack();
echo $db->query('SELECT COUNT(*) FROM inventory')->fetchColumn(), PHP_EOL;The rollback undoes the insert and the count prints 0. Calling commit instead would retain the row for the lifetime of this database connection.
Composer and autoloading
Install a project dependency
Install Composer 2 from Resources, then run this command in a new project directory.
composer require "psr/log:^3.0"Composer records the requirement in composer.json, resolves a version in composer.lock, and installs it under vendor. Commit both manifest and lock file for an application so composer install can reproduce the resolution.
Load a namespaced class
Save this script beside composer.json after installing the dependency.
<?php
use Psr\Log\NullLogger;
require __DIR__ . '/vendor/autoload.php';
$logger = new NullLogger();
$logger->info('Inventory loaded');
echo get_class($logger), PHP_EOL;The generated autoloader finds NullLogger when PHP first references the class. The script prints Psr\Log\NullLogger. NullLogger discards the log message.
Testing behavior
Check a normal result
Use a small CLI smoke test to verify a deterministic calculation without any dependencies.
<?php
function subtotal(int $unitPrice, int $count): int
{
return $unitPrice * $count;
}
if (subtotal(7, 3) !== 21) {
fwrite(STDERR, "Wrong subtotal\n");
exit(1);
}
echo "Subtotal passed\n";The script prints Subtotal passed and exits with status 0. Changing the expected value to 20 prints Wrong subtotal to standard error and exits with status 1.
Check rejected input
Test the failure path by giving a function a quantity outside its allowed range.
<?php
function validateQuantity(int $count): void
{
if ($count < 0) {
throw new InvalidArgumentException('Negative quantity');
}
}
try {
validateQuantity(-1);
} catch (InvalidArgumentException $error) {
echo "Negative quantity rejected\n";
exit(0);
}
fwrite(STDERR, "Expected InvalidArgumentException\n");
exit(1);The expected exception produces Negative quantity rejected and status 0. If the call returns normally, execution reaches the failure message and status 1.
Best Practices
Escape values in HTML
Render text in an element
Escape user-supplied text before inserting it between HTML tags.
<?php
$name = '<Ada>';
echo '<p>' . htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</p>', PHP_EOL;The generated markup contains <Ada> between the paragraph tags. A browser displays the angle brackets as text.
Keep data inside a quoted attribute
Quote the attribute and escape the supplied value, including quotation marks.
<?php
$label = 'A "quoted" value';
echo '<input value="' . htmlspecialchars($label, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '">', PHP_EOL;The output replaces each inner quote with an HTML entity. The browser reads the quotes as part of one value attribute. JavaScript, CSS, and URL contexts require their own handling.
Immutable value objects
Validate during construction
Use a readonly class to keep simple domain values fixed after construction.
<?php
final readonly class Quantity
{
public function __construct(public int $units)
{
if ($units < 0) {
throw new InvalidArgumentException('Quantity must be non-negative');
}
}
}
echo (new Quantity(3))->units, PHP_EOL;A valid quantity prints 3. A negative quantity raises InvalidArgumentException before the object can represent invalid state.
Return a changed copy
Return a new value when a calculation should preserve the original object for later use.
<?php
final readonly class Amount
{
public function __construct(public int $cents)
{
}
public function plus(self $other): self
{
return new self($this->cents + $other->cents);
}
}
$original = new Amount(150);
$updated = $original->plus(new Amount(50));
echo $original->cents, PHP_EOL;
echo $updated->cents, PHP_EOL;Adding 50 creates a new Amount with 200 cents. The original remains at 150, so the lines print 150 and 200.
Resource cleanup
Close a stream in finally
Place fclose in a finally block so a successfully opened stream is released even if processing throws.
<?php
$stream = fopen('php://temp', 'w+');
if ($stream === false) {
throw new RuntimeException('Could not open stream');
}
try {
fwrite($stream, 'tea');
rewind($stream);
echo stream_get_contents($stream), PHP_EOL;
} finally {
fclose($stream);
}The script prints tea and then closes the temporary stream before execution leaves the block.
Observe cleanup before an error handler
Catch an error outside the block that owns the resource so cleanup completes before the handler runs.
<?php
$stream = fopen('php://temp', 'w+');
if ($stream === false) {
throw new RuntimeException('Could not open stream');
}
try {
try {
throw new UnexpectedValueException('Invalid record');
} finally {
fclose($stream);
echo "Stream closed\n";
}
} catch (UnexpectedValueException $error) {
echo $error->getMessage(), PHP_EOL;
}The exception leaves the inner try block, so finally prints Stream closed before the outer handler prints Invalid record.