SEO Metadata
SEO Title Options
- PHP 8.2 Released: Readonly Classes, DNF Types
- PHP Core PHP: Practical 2026 Guide
- Core PHP Playbook: PHP Core PHP
Meta Description Options
- Learn PHP Core PHP with a practical Core PHP framework, expert mistakes, implementation steps, examples, FAQ, and schema-ready guidance.
- First look at PHP 8.2 features — readonly classes, Disjunctive Normal Form types, new ini options, and upcoming deprecation clean-ups.
URL Slug
php-82-released-readonly-classes-dnf-types-deprecations-explained
Focus Keyword
PHP Core PHP
Additional LSI Keywords
- Core PHP
- PHP
- PHP 8.2
- Type System
- Migration
- PHP 8.2 Released: Readonly Classes, DNF Types & Deprecations Explained
- production checklist
- implementation guide
- best practices
- architecture decisions
- testing strategy
- performance impact
Table of Contents
- Article overview
- What PHP Core PHP means
- Why it matters now
- Implementation framework
- Practical comparison
- Expert workflow
- Common mistakes
- Media and link plan
- Original technical deep dive
- FAQ
- Structured data
- Conclusion
Article overview
PHP Core PHP is the kind of topic that looks simple until it reaches production. Teams usually discover the real cost late: unclear boundaries, weak defaults, hidden maintenance work, and decisions that seemed harmless when the codebase was small.
The problem gets worse when the article, tutorial, or implementation guide only explains the happy path. This guide closes that gap with a practical framework, a comparison table, common mistakes, and a deep technical section you can use while planning real work.
Keep reading for the non-obvious part: the safest implementation is rarely the most impressive-looking one. It is the one your team can debug, test, document, and evolve without turning every future change into archaeology.
Key Takeaways
- PHP Core PHP should be evaluated as a production decision, not only as a syntax or tooling choice.
- The best implementation keeps responsibilities visible, with clear ownership, tests, documentation, and rollback paths.
- Search visibility improves when practical depth, structured answers, and expert examples live on the same page.
[IMAGE: A mobile-first technical article layout showing the main concept, decision table, implementation checklist, and FAQ blocks. Alt: PHP Core PHP expert guide for Core PHP]
What PHP Core PHP means
PHP Core PHP means applying core php knowledge to a concrete engineering decision, then turning that decision into reliable code, documentation, and operational behavior. In practice, it combines the topic's core concepts with trade-off analysis, implementation boundaries, testing strategy, and maintenance discipline.
This is the definition worth optimizing for featured snippets because it avoids hype. It tells the reader what the topic does and what a professional implementation must include.
Why it matters now
The technical web is more crowded than it was a few years ago. Thin tutorials can still get indexed, but they rarely earn trust from senior developers, buyers, AI answer systems, or teams that need production guidance.
For core php topics, the strongest content now has three layers:
- a clear answer for fast scanning
- a practical framework for implementation
- expert context that explains what breaks later
That same structure helps search engines understand the page. It also helps readers decide whether the advice fits their project.
Implementation framework
Use this framework before adopting the approach described in this article.
- Define the user problem and the production risk.
- Identify the smallest reliable implementation boundary.
- Keep configuration, secrets, and environment-specific behavior outside the article's core logic.
- Add tests for the behavior that would hurt if it regressed.
- Document the trade-off, not only the final code.
- Measure the result with logs, metrics, or user-facing outcomes.
- Revisit the decision after real usage exposes edge cases.
The sequence is deliberately conservative. It keeps the work grounded in outcomes instead of novelty.
[IMAGE: A seven-step implementation framework with discovery, boundary design, configuration, tests, documentation, measurement, and iteration. Alt: PHP Core PHP implementation framework]
Practical comparison
| Decision area | Strong approach | Weak approach | Why it matters |
|---|---|---|---|
| Scope | Solve one clear problem | Mix unrelated concerns | Focus improves testing and search intent |
| Architecture | Put logic in explicit classes or documented boundaries | Hide behavior in templates or incidental callbacks | Future changes stay easier to review |
| Data flow | Pass prepared data into the view or endpoint | Query or compute in presentation code | Reduces regressions and performance surprises |
| Testing | Cover the risky behavior directly | Test only the happy path | Catches production failures earlier |
| Documentation | Explain trade-offs and limits | Repeat generic definitions | Builds E-E-A-T and reader trust |
| Operations | Track logs, metrics, and rollback steps | Ship without measurement | Makes the decision reversible |
This table is intentionally practical. It gives a reviewer something to check before the implementation becomes expensive to change.
Expert workflow
Expert tip: "Treat PHP Core PHP as a system boundary. If the next developer cannot find where the decision lives, how it is tested, and when it should be avoided, the implementation is not finished."
A useful workflow is simple:
- Start with the smallest working example.
- Add the constraints that exist in your real project.
- Remove anything that only demonstrates cleverness.
- Write down the failure modes.
- Add links to related decisions so future readers can navigate the topic cluster.
That last point matters for both humans and search systems. A single article can answer a question; a cluster proves authority.
Common mistakes
Mistake 1: Copying a pattern without its context
A pattern that works in a small demo can fail in a real application. The missing context is usually data volume, team experience, deployment process, security requirements, or observability.
Before copying the pattern, ask what assumption made it safe in the original example.
Mistake 2: Putting business logic in the wrong layer
This is the fastest way to make future debugging expensive. In Laravel, PHP, and server-rendered websites, presentation should receive prepared data, not discover rules on its own.
Keep decision logic in models, actions, services, policies, requests, jobs, or documented helpers where it can be tested directly.
Mistake 3: Optimizing for novelty instead of maintainability
Newer tools and language features can be valuable. They can also hide simple behavior behind unfamiliar syntax.
Use the option that makes the next production incident easier to understand.
Mistake 4: Publishing without a measurement plan
If the article describes a performance, SEO, security, or architecture improvement, define how success will be checked. Logs, tests, crawl diagnostics, analytics, and user behavior are all stronger than assumptions.
[IMAGE: A common-mistakes board with context loss, wrong layer, novelty bias, and missing measurement highlighted. Alt: PHP Core PHP common mistakes]
Media and link plan
Image placeholders
- [IMAGE: A concept diagram for PHP Core PHP with input, decision boundary, implementation, tests, and production feedback. Alt: PHP Core PHP concept diagram]
- [IMAGE: A mobile screenshot-style checklist for PHP 8.2 Released: Readonly Classes, DNF Types & Deprecations Explained. Alt: PHP Core PHP mobile checklist]
- [IMAGE: A comparison table visualization for strong versus weak implementation choices. Alt: PHP Core PHP comparison table]
Video placeholder
[VIDEO: Insert a 5-8 minute YouTube walkthrough that demonstrates the main decision, the implementation boundary, the test strategy, and the production caveats for PHP Core PHP.]
Trustworthy outbound links
- PHP manual - use this as the trust reference for language-level reference.
- Google Search quality guidance - use this as the trust reference for people-first content and E-E-A-T alignment.
Internal linking opportunities
- Internal guide: PHP 8.3 Features: Typed Class Constants - use this when readers need a related Core PHP follow-up.
- Internal guide: PHP Type System Mastery: Union, Intersection - use this when readers need a related Core PHP follow-up.
Original Technical Deep Dive
Historical note
This post is dated January 19, 2022 because it belongs to the editorial timeline of this blog series. PHP 8.2 was not generally available on that date.
The first official PHP 8.2 testing release, PHP 8.2.0 Alpha 1, arrived on June 9, 2022. PHP 8.2.0 was officially released on December 8, 2022.
So read this as an updated release guide: it keeps the original "first look" framing, but the details below are based on the final PHP 8.2 behavior.
The short version
PHP 8.2 is not a huge syntax rewrite. It is a cleanup release with a few sharp language improvements:
readonly classremoves repetitivereadonlyproperty declarations.- DNF types allow combinations like
(Countable&IteratorAggregate)|null. true,false, andnullcan be used as stand-alone types.- The new
Randomextension gives random number generation a cleaner object-oriented API. - Constants can be declared in traits.
#[SensitiveParameter]can hide secrets from stack traces.error_log_modeallows configuring permissions for the PHP error log file.- Dynamic properties,
${var}interpolation,utf8_encode(), andutf8_decode()are deprecated.
The release nudges PHP code toward explicit models, explicit properties, explicit types, and explicit migration work.
Readonly classes
PHP 8.1 introduced readonly properties:
declare(strict_types=1);
final class BlogPostData
{
public function __construct(
public readonly string $title,
public readonly string $slug,
public readonly DateTimeImmutable $publishedAt,
) {
}
}
PHP 8.2 lets the whole class be marked readonly:
declare(strict_types=1);
readonly final class BlogPostData
{
public function __construct(
public string $title,
public string $slug,
public DateTimeImmutable $publishedAt,
) {
}
}
Every instance property is readonly. You can assign it during construction, but not later:
$post = new BlogPostData(
title: 'PHP 8.2 Released',
slug: 'php-82-released',
publishedAt: new DateTimeImmutable('2022-12-08'),
);
$post->title = 'Changed';
That last assignment fails.
Readonly classes are useful for:
- DTOs.
- Value objects.
- Query results.
- Configuration snapshots.
- Event payloads.
- Immutable command objects.
They are not a replacement for every class. Entities with real lifecycle changes should not usually be readonly:
final class Invoice
{
private InvoiceStatus $status;
public function markPaid(): void
{
$this->status = InvoiceStatus::Paid;
}
}
If the object changes state as part of the domain model, making it readonly fights the model.
Readonly class restrictions
Readonly classes are stricter than normal classes.
Every instance property must be typed:
readonly class InvalidData
{
public $title;
}
That is invalid because the property has no type.
Static properties are not part of object immutability and cannot be readonly instance state:
readonly class InvalidCounter
{
public static int $count = 0;
}
Readonly classes also cannot use dynamic properties:
readonly class UserData
{
public function __construct(public string $name)
{
}
}
$user = new UserData('Ada');
$user->nickname = 'ada';
That does not fit the readonly model. Declare the property or do not store it there.
Good readonly class example
A practical DTO:
declare(strict_types=1);
readonly final class CreateUserCommand
{
public function __construct(
public string $email,
public string $plainPassword,
public string $displayName,
) {
if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Invalid email address.');
}
if (strlen($plainPassword) < 12) {
throw new InvalidArgumentException('Password is too short.');
}
}
}
This is a good fit because the command represents an input message. It should not mutate after creation.
[IMAGE: Supporting visual 1 for PHP 8.2 Released: Readonly Classes, DNF Types & Deprecations Explained, showing PHP Core PHP decisions, examples, and PHP, PHP 8.2, Core PHP. Alt: PHP Core PHP php-82-released-readonly-classes-dnf-types-deprecations-explained visual 1]
[IMAGE: Supporting visual 1 for PHP 8.2 Released: Readonly Classes, DNF Types & Deprecations Explained, showing PHP Core PHP decisions, examples, and PHP, PHP 8.2, Core PHP. Alt: PHP Core PHP php-82-released-readonly-classes-dnf-types-deprecations-explained visual 1]
DNF types
PHP already had union types:
function findUser(): User|null
{
// ...
}
PHP already had intersection types:
function export(IteratorAggregate&Countable $items): void
{
// ...
}
PHP 8.2 allows them to be combined in Disjunctive Normal Form:
function export((IteratorAggregate&Countable)|array $items): void
{
// ...
}
The intersection part must be grouped with parentheses.
This means:
The value may be an array,
or it may be an object that is both IteratorAggregate and Countable.
The type is explicit. The old version would often be mixed plus runtime checks:
function export(mixed $items): void
{
if (! is_array($items) && ! $items instanceof IteratorAggregate) {
throw new InvalidArgumentException('Invalid export source.');
}
if ($items instanceof IteratorAggregate && ! $items instanceof Countable) {
throw new InvalidArgumentException('Export source must be countable.');
}
}
DNF types move that contract into the signature:
function export((IteratorAggregate&Countable)|array $items): void
{
// ...
}
Use DNF types when the shape is genuinely part of the public contract. Do not use them to impress the reader.
DNF types in service contracts
Example:
interface CsvExporter
{
public function export((Traversable&Countable)|array $records): string;
}
This is useful because the exporter needs to iterate and know the count for progress reporting or header metadata.
Another example:
interface ReportRenderer
{
public function render((JsonSerializable&Stringable)|array $data): string;
}
This says the renderer accepts either:
- An array payload.
- An object that can be serialized to JSON and converted to a string.
That may be clearer than a loose mixed, but only if callers already understand why both capabilities are required.
If a signature starts to look like a puzzle, introduce an interface:
interface ReportData extends JsonSerializable, Stringable
{
}
interface ReportRenderer
{
public function render(ReportData|array $data): string;
}
Names are often better than clever type algebra.
Stand-alone true, false, and null types
PHP 8.0 allowed false in union types for legacy APIs:
function loadConfig(): array|false
{
// ...
}
PHP 8.2 allows false, true, and null as stand-alone types:
function featureDisabled(): false
{
return false;
}
function featureEnabled(): true
{
return true;
}
function noResult(): null
{
return null;
}
This is niche, but useful for narrowing child method return types and documenting sentinel APIs.
Example:
interface AuthorizationResult
{
public function allowed(): bool;
}
final class Denied implements AuthorizationResult
{
public function allowed(): false
{
return false;
}
}
That is more precise than bool, but do not overuse it. Most application code should still return meaningful objects instead of encoding too much meaning into true, false, or null.
Dynamic properties are deprecated
This is the migration item most legacy PHP applications feel first.
Before PHP 8.2:
final class User
{
public string $name;
}
$user = new User();
$user->name = 'Ada';
$user->email = 'ada@example.com';
email is a dynamic property. It was not declared on the class.
In PHP 8.2, creating that property emits a deprecation notice.
Fix it by declaring the property:
final class User
{
public string $name;
public string $email;
}
If you intentionally need dynamic properties, use #[AllowDynamicProperties]:
#[AllowDynamicProperties]
final class LegacyRecord
{
}
Use that as a temporary bridge, not a default design. Declared properties are easier to analyze, refactor, and validate.
stdClass still allows dynamic properties:
$payload = new stdClass();
$payload->email = 'ada@example.com';
Classes with __get() and __set() are also not affected in the same way because the property access is handled explicitly.
[IMAGE: Supporting visual 2 for PHP 8.2 Released: Readonly Classes, DNF Types & Deprecations Explained, showing PHP Core PHP decisions, examples, and PHP, PHP 8.2, Core PHP. Alt: PHP Core PHP php-82-released-readonly-classes-dnf-types-deprecations-explained visual 2]
Finding dynamic properties
Turn deprecations into visible signals in development and CI:
error_reporting=E_ALL
display_errors=1
log_errors=1
Then run tests on PHP 8.2.
For applications without enough tests, add runtime logging around deprecations in staging:
set_error_handler(static function (
int $severity,
string $message,
string $file,
int $line,
): bool {
if ($severity === E_DEPRECATED) {
error_log("Deprecated: {$message} in {$file}:{$line}");
}
return false;
});
[IMAGE: Supporting visual 2 for PHP 8.2 Released: Readonly Classes, DNF Types & Deprecations Explained, showing PHP Core PHP decisions, examples, and PHP, PHP 8.2, Core PHP. Alt: PHP Core PHP php-82-released-readonly-classes-dnf-types-deprecations-explained visual 2]
Do not suppress dynamic property deprecations globally. They often reveal real typos:
$user->emial = 'ada@example.com';
That typo silently creates a useless property in older PHP versions. PHP 8.2 helps you catch it.
Deprecated string interpolation
PHP 8.2 deprecates "${var}" and "${expr}" style interpolation.
Replace this:
$message = "Hello ${name}";
with this:
$message = "Hello {$name}";
Replace this:
$message = "Hello ${$propertyName}";
with this:
$message = "Hello {${$propertyName}}";
The simple "$name" form still works:
$message = "Hello $name";
For project code, prefer braces when interpolation touches anything non-trivial:
$message = "Order {$orderId} was paid by {$customerEmail}.";
It is clearer in review and safer during refactors.
utf8_encode and utf8_decode are deprecated
utf8_encode() and utf8_decode() are deprecated in PHP 8.2.
The names were always misleading. They convert between ISO-8859-1 and UTF-8, not between arbitrary encodings and UTF-8.
Replace them with explicit encoding conversion:
$utf8 = mb_convert_encoding($value, 'UTF-8', 'ISO-8859-1');
or:
$latin1 = mb_convert_encoding($value, 'ISO-8859-1', 'UTF-8');
The correct replacement depends on what the source encoding actually is.
Do not blindly swap function names. First identify the input encoding at the boundary: file import, database connection, legacy API, or user upload.
SensitiveParameter attribute
PHP 8.2 adds #[SensitiveParameter] to redact sensitive values in backtraces.
declare(strict_types=1);
function connectToApi(
string $endpoint,
#[SensitiveParameter] string $token,
): void {
throw new RuntimeException('Connection failed.');
}
connectToApi('https://api.example.com', 'secret-token');
The token should not be exposed in stack traces.
Use it for:
- Passwords.
- API tokens.
- Private keys.
- Session secrets.
- Authorization headers.
- One-time codes.
This does not replace secret management. It only reduces accidental leakage when errors are logged or displayed.
New Random extension
PHP 8.2 introduces the Random extension with an object-oriented API.
declare(strict_types=1);
use Random\Randomizer;
$randomizer = new Randomizer();
$code = $randomizer->getInt(100000, 999999);
$shuffled = $randomizer->shuffleArray(['a', 'b', 'c']);
The default Randomizer uses a cryptographically secure engine.
For repeatable tests or simulations, pass a specific engine:
use Random\Engine\Mt19937;
use Random\Randomizer;
$randomizer = new Randomizer(new Mt19937(1234));
$first = $randomizer->getInt(1, 100);
$second = $randomizer->getInt(1, 100);
Use secure defaults for tokens, codes, and security-sensitive randomness. Use seeded engines only when repeatability is the goal.
Constants in traits
PHP 8.2 allows constants inside traits:
trait HasStatusCodes
{
public const STATUS_ACTIVE = 'active';
public const STATUS_DISABLED = 'disabled';
}
final class UserStatus
{
use HasStatusCodes;
}
echo UserStatus::STATUS_ACTIVE;
The constant is accessed through the class using the trait, not through the trait name.
This is useful for shared behavior where constants are genuinely tied to the trait. If a constant is part of a broader domain concept, an enum or dedicated value object may be clearer.
[IMAGE: Supporting visual 3 for PHP 8.2 Released: Readonly Classes, DNF Types & Deprecations Explained, showing PHP Core PHP decisions, examples, and PHP, PHP 8.2, Core PHP. Alt: PHP Core PHP php-82-released-readonly-classes-dnf-types-deprecations-explained visual 3]
New ini options
PHP 8.2 adds error_log_mode:
error_log=/var/log/php/app-error.log
error_log_mode=0640
This controls permissions for the error log file created by PHP.
That matters in production because log files often contain request paths, stack traces, user identifiers, or operational details. Set permissions deliberately instead of relying on defaults.
PHP 8.2 also adds OCI8 options for reducing round trips when fetching large objects from Oracle Database:
oci8.prefetch_lob_size=1048576
[IMAGE: Supporting visual 3 for PHP 8.2 Released: Readonly Classes, DNF Types & Deprecations Explained, showing PHP Core PHP decisions, examples, and PHP, PHP 8.2, Core PHP. Alt: PHP Core PHP php-82-released-readonly-classes-dnf-types-deprecations-explained visual 3]
This is only relevant for applications using OCI8 with supported Oracle versions. Most PHP applications will care more about error_log_mode.
Backward incompatible changes worth testing
Several PHP 8.2 changes are not headline features but can affect real applications.
Some string case functions are no longer locale-sensitive:
strtolower('I');
strtoupper('i');
These now perform ASCII case conversion as if the locale were C. If you need localized case behavior, use MBString functions designed for multibyte strings.
str_split('') now returns an empty array:
str_split('');
Before PHP 8.2, code may have expected an array containing one empty string.
glob() behavior around open_basedir changed. If your application runs in restricted hosting or sandboxed paths, test file discovery code.
Some SPL methods enforce signatures more strictly. If you extend SPL classes, run the test suite on PHP 8.2 and fix method signatures instead of suppressing warnings.
Migration plan
Do not start by converting every DTO to readonly class.
Start with compatibility:
- Run the test suite on PHP 8.2 with
E_ALL. - Fix dynamic property deprecations.
- Replace deprecated
${var}interpolation. - Replace
utf8_encode()andutf8_decode()with explicit encoding conversion. - Check custom classes that extend SPL classes.
- Test locale-sensitive string behavior if the application depends on locales.
- Update static analysis and coding standards.
- Only then introduce new PHP 8.2 syntax.
New syntax should come after compatibility work. Otherwise, the upgrade becomes harder to review because behavior fixes and style improvements are mixed together.
Where readonly classes fit first
Good first candidates:
src/Application/*Command.php
src/Application/*Query.php
src/Application/*Result.php
src/Shared/Clock/Timestamp.php
src/Shared/Config/*.php
[IMAGE: Supporting visual 4 for PHP 8.2 Released: Readonly Classes, DNF Types & Deprecations Explained, showing PHP Core PHP decisions, examples, and PHP, PHP 8.2, Core PHP. Alt: PHP Core PHP php-82-released-readonly-classes-dnf-types-deprecations-explained visual 4]
Riskier candidates:
Doctrine entities
Eloquent models
Objects hydrated by serializers
Objects mutated across workflow steps
Classes using magic properties
Framework hydration and readonly objects can conflict if the framework expects to assign properties after construction. Test those paths before broad refactors.
Composer platform strategy
Raise the platform requirement only when the application and deployment stack are ready:
{
"require": {
"php": "^8.2"
},
"config": {
"platform": {
"php": "8.2.0"
}
}
}
For libraries, be more conservative. If the library can support PHP 8.1, do not require PHP 8.2 only to use readonly classes internally.
For applications, the requirement can be stricter because deployment is under your control.
CI matrix
During migration, run old and new PHP versions:
strategy:
matrix:
php:
- '8.1'
- '8.2'
steps:
- uses: actions/checkout@v3
- uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
- run: composer install --no-interaction --prefer-dist
- run: composer test
Once production is fully on PHP 8.2, remove the older version from the required matrix and keep it only if you still publish reusable packages for it.
[IMAGE: Supporting visual 4 for PHP 8.2 Released: Readonly Classes, DNF Types & Deprecations Explained, showing PHP Core PHP decisions, examples, and PHP, PHP 8.2, Core PHP. Alt: PHP Core PHP php-82-released-readonly-classes-dnf-types-deprecations-explained visual 4]
Practical checklist
- Did the test suite run on PHP 8.2 with
E_ALL? - Are dynamic properties declared, removed, or intentionally allowed?
- Are
${var}and${expr}interpolations cleaned up? - Are
utf8_encode()andutf8_decode()replaced with explicit conversions? - Are SPL overrides compatible with PHP 8.2 signatures?
- Are locale-sensitive string assumptions tested?
- Are readonly classes used only for objects that should not mutate?
- Are DNF types used where they clarify a real contract?
- Are secret parameters marked with
#[SensitiveParameter]where stack traces may expose them? - Is
error_log_modeconfigured in production?
PHP 8.2 rewards explicit code. The safest upgrade path is to fix ambiguity first, then adopt the new syntax where it makes the design easier to understand.
FAQ
What is PHP Core PHP?
PHP Core PHP is a practical core php topic that should be evaluated through implementation scope, production risk, testing, documentation, and long-term maintainability.
When should a team use PHP Core PHP?
Use PHP Core PHP when it solves a real project constraint, improves clarity, or reduces operational risk. Avoid it when it only adds novelty or hides behavior from future maintainers.
What is the biggest risk with PHP Core PHP?
The biggest risk is copying a pattern without its context. Production systems need clear boundaries, rollback options, tests, and observability before a technique becomes dependable.
How do you test PHP Core PHP?
Test the smallest unit that owns the behavior, then add integration coverage for the path users or systems actually rely on. Include failure cases, configuration differences, and regression checks.
How does PHP Core PHP affect SEO and AI search visibility?
It improves visibility when the article gives a direct answer, expert context, structured headings, internal links, trustworthy references, and FAQ content that matches the visible page.
Conclusion
PHP Core PHP is worth doing when the implementation improves clarity, reliability, or delivery speed. It is not worth doing when it hides ownership, increases operational risk, or makes the system harder to explain.
Use the framework above as a review checklist. Then connect this topic to the rest of the project documentation so readers can move from concept to implementation without losing context.