PHP Development Best Practices
skillWrites and reviews typed PHP in Composer projects: runtime compatibility, PHP 8.5 pipes, PHP 8.6 partial function application, and migration checks.
agents that use this skill
instructions
Overview
Write clear PHP with explicit types, validated inputs, and small, cohesive functions and objects. Apply modern features where they simplify the task; preserve existing project conventions except for the brace rule below.
Mental model
PHP is dynamically typed with optional declarations and opt-in strict scalar checking. Types describe values; validation checks inputs; constructors and mutations enforce business invariants.
Runtime
- PHP 8.6 reached GA on 2026-11-19. As of 2026-12-03, PHP.net lists 8.6.0 and 8.5.13 as the latest releases in those branches. Check PHP.net for current patches and support dates; use the latest patch of the chosen supported branch, not the version in this snapshot.
- For a version-sensitive answer or edit, check the official release notes, migration guide, and manual rather than relying on model recall or treating an accepted RFC as proof of availability. Reproduce unfamiliar syntax with
php -land a small behavior test on the target interpreter; report if only documentation was checked. - Determine the minimum runtime from Composer requirements,
config.platform, CI, and deployment. Match syntax, extensions, dependencies, and analyzer settings to that minimum. A runtime condition cannot hide unsupported syntax in the same file. - Composer's platform setting simulates dependency resolution, not runtime compatibility. Verify with
composer check-platform-reqsin the target environment. Preserve version constraints unless an upgrade is requested.
Style and design
- Always place function, method, and closure opening braces on the final signature line:
function name(): void {. For multiline signatures, place the brace after the closing parenthesis and any return type. This overrides PER/PSR-12 brace placement. - Follow other repository formatting rules. Without an existing standard, use PHP-FIG PER Coding Style (3.1 at research time) with this brace exception.
- Use descriptive names, guard clauses, and focused functions. Prefer a clear loop to clever callbacks or nested ternaries. Add abstractions for real responsibilities, not pattern compliance.
- Inject dependencies; separate calculations from I/O. Preserve framework/ORM conventions and Composer PSR-4 mappings. Don't introduce layers, repository wrappers, or a message bus for simple CRUD.
- Keep request state out of shared long-running services. Respect ORM/proxy requirements before adding
final, readonly properties, or hooks.
Types and correctness
- Use
declare(strict_types=1);in new PHP files; assess coercion changes before adding it to existing files. Scalar argument strictness follows the caller's file and does not validate external data. - Type parameters, returns, and properties. Narrow external
mixed; use PHPDoc only for additional contracts such aslist<User>, array shapes, and generics. PHPDoc is not runtime validation. - Prefer constructor promotion and readonly value objects for stable data. Readonly is shallow: contained objects can still mutate. Prefer
DateTimeImmutablefor immutable dates. - Enforce invariants at construction and mutation, including CLI/queue callers. An
intis not necessarily positive. Use integer minor units or decimal arithmetic for exact money. - Use enums for closed sets, backed enums for scalar serialization, and constants for independent values. Validate scalar types before
tryFrom(); usefrom()when invalid values should throw. - Prefer
===, strictin_array(..., true), and explicit absence checks.empty()conflates zero/false with absence;isset()and??conflate null with missing keys. Usearray_key_exists()when needed. - Use
matchfor strict selection and?->for expected absence. Don't hide unhandled enum cases with a fallback. Named arguments couple callers to parameter names.
Modern features
Use only when the minimum runtime and tooling support them.
| PHP | Useful features | Important limits |
|---|---|---|
| 8.3 | Typed class constants; #[\Override] on methods | Preserve parent/interface contracts. |
| 8.4 | Property hooks; public private(set) | Keep hooks local and free of I/O. Hooked properties cannot be readonly; restricted setters still permit internal mutation. |
| 8.4 | array_find(), array_find_key(), array_any(), array_all(); native lazy objects | Use the key variant to distinguish a matched null from absence. Let compatible frameworks manage lazy objects. |
| 8.5 | |> pipe operator | The left value is passed as one argument to the callable on the right: $value |> trim(...). Use a closure to bind other arguments on 8.5; ? placeholders require 8.6. |
| 8.5 | Static closures and first-class callables in constant expressions | Use static function (...) { ... }, not static fn, in constants, defaults, or attribute arguments. Arbitrary calls still aren't constant expressions. |
| 8.5 | clone($object, ['property' => $value]); #[\NoDiscard] | Clone-with can update readonly properties where setter visibility permits. It is shallow and does not rerun the constructor. Use (void) only for intentional discards. |
| 8.5 | array_first(), array_last(); Uri\Rfc3986\Uri, Uri\WhatWg\Url | Endpoint helpers return null for empty arrays or stored null values. Choose the required URL standard; parsing does not authorize destinations. |
| 8.5–8.6 | #[\Override] on more declarations | Methods since 8.3, properties since 8.5, class constants and enum cases since 8.6. PHP 8.5 also adds asymmetric visibility for static properties. |
| 8.6 | Readonly instance-property defaults; parameter doc comments | A default initializes the readonly property, so the constructor cannot overwrite it. Read parameter comments via ReflectionParameter::getDocComment(). ReflectionProperty::isReadable() and isWritable() expose read/write capability. |
| 8.6 | Time\Duration, clamp($value, $min, $max), SortDirection | Use Duration for elapsed time and timeouts, not calendar intervals. Clamp accepts comparable values; use SortDirection::Ascending or SortDirection::Descending for typed sort APIs. |
| 8.6 | Io\Poll; structured stream errors | Poll provides scalable stream readiness monitoring for event loops. Opt into stream exceptions with StreamErrorMode::Exception; align handling with the project's existing I/O conventions. |
Partial function application (PHP 8.6+)
Bind arguments now and get a Closure without calling the target. Bound expressions are evaluated once when the closure is created, unlike expressions in an arrow function body.
?leaves one required argument, even if the original parameter had a default. A named placeholder such assubject: ?comes after positional arguments; named placeholders set the order of the corresponding closure parameters.- A bare
...forwards the remaining parameters, preserving defaults and variadics; use it at most once and only last.trim(...)alone is the existing first-class callable syntax, available since 8.1. Without..., extra positional arguments to the partial closure are not forwarded. - The closure preserves exposed parameter types, pass-by-reference modes, and the original return type. Partial calls can be constant expressions when their bound arguments are constant expressions and the callable is valid there.
- Don't combine placeholders with
new,?->, or argument unpacking. Keep an arrow function on PHP 8.5 and earlier; a runtime version check cannot hide 8.6 syntax from an older parser.
$versions = ['8.4', '8.5', '8.6', '8.7', '9.0'];
$supported = array_filter($versions, version_compare(?, '8.6', '>='));
$normalized = 'in-progress' |> str_replace('-', '_', ?); // 'in_progress'For a PHP 8.5-compatible filter, pass static fn (string $version): bool => version_compare($version, '8.6', '>=') instead. Prefer a closure when binding time, argument order, or extra arguments would make the partial call harder to read.
Upgrade checks
Read each crossed version's migration guide. Avoid ordinary dynamic properties (deprecated in 8.2) and implicit nullability (deprecated in 8.4); use explicit ?T $value = null where appropriate.
- 8.5: use canonical casts such as
(int)and(bool), not deprecated aliases; replace backtick execution.disable_classeswas removed. Audit nullable array keys instead of silently converting missing IDs to empty strings. - 8.6: remove
returnfromfinallyblocks; it is deprecated and can swallow an exception or override a return value. Review session defaults (strict mode, HttpOnly and SameSite=Lax), custom session handlers, form-feed trimming, and stream writes that can now returnfalseon flush or close failure.
Boundaries and errors
- Decode JSON with
JSON_THROW_ON_ERROR, then validate shape and values. Don't cast malformed input into plausible data or deserialize untrusted PHP objects. - Preserve established exception/result conventions. Catch specific failures, retain exception causes, and use
finallyfor owned resources. CatchThrowableat execution boundaries where appropriate; don't turn programming bugs into success. - Bind SQL values; allowlist identifiers and sort directions. Use transactions, database constraints, and appropriate locking for related writes. Bound queries, prevent N+1 access, and preserve applied migrations.
- Make retried mutations idempotent and coordinate external effects with durable state. Validate and authorize separately; serialize explicit responses and escape output for its destination. Use password hashing APIs and cryptographic random tokens; exclude secrets from logs.
Example
Validate a positive integer without coercing strings, floats, or booleans:
<?php
declare(strict_types=1);
function positiveInt(mixed $value): int {
if (!is_int($value) || $value < 1) {
throw new InvalidArgumentException('Expected a positive integer.');
}
return $value;
}positiveInt(2) succeeds; '2', 2.5, true, 0, and null fail. Domain objects must also enforce their own invariants.
Checklist
- Runtime, dependencies, syntax, and analyzer targets agree.
- Braces follow the same-line rule; new abstractions improve clarity.
- Inputs, invariants, authorization, and persistence behavior are checked.
- Relevant syntax/style checks, PHPStan or Psalm, and PHPUnit or Pest pass using existing project tooling and execution permissions. Test behavior and failure cases; use strict assertions where types matter.
- Dependency changes include Composer validation, platform checks, and an advisory audit. Report unexecuted checks; don't suppress findings or broadly update dependencies to make checks pass.
References
- Versions and upgrades: support table, 8.3 migration, 8.4 migration, 8.5 release and migration, 8.6 release and migration.
- PHP 8.6 partial function application: release example and language manual.
- Language semantics: types, properties, hooks, cloning.
- Tooling: PER style, PHPStan types, Composer platform.