Skip to content
Tutorials Center
My learning

Topics

Lesson 119 of 147 ยท Modern PHP and Ecosystem

What's New in PHP 8.0 to 8.5

A tour of every PHP 8 release - match, enums, readonly, property hooks, the pipe operator, clone with and more - with runnable examples, deprecations and upgrade tips.

PHP has changed more since 2020 than in the ten years before. PHP 8.0 brought a new type-checking culture, named arguments and match; every release since has added language features that make code shorter and safer: enums, readonly classes, property hooks, and in PHP 8.5 the pipe operator. If you learned PHP from older books or answers online, much of the "PHP way" you saw is now outdated.

This lesson is a tour of PHP 8.0 through 8.5, release by release. Each version gets a short list of its headline features and a runnable example, plus links to the lessons that cover each feature in depth. It ends with the deprecations you're most likely to hit and a practical upgrade checklist. Our editor runs PHP 8.5, so every example here works as written.

The release cycle in brief

A new PHP version comes out every year, near the end of November. Each version gets two years of active support (bug fixes) and then two years of security fixes only, four years in total. After that it's end of life: no fixes at all, even for security holes. In practice that means you should plan to upgrade roughly once a year, and never run a version that's past its security support on a public server.

Versions follow major.minor.patch. Patch releases (8.5.1, 8.5.2, ...) only fix bugs and are safe to install right away. Minor releases (8.4 to 8.5) add features and deprecations but rarely break working code. Major releases (7 to 8) remove deprecated features and can break code.

PHP 8.0 (November 2020)

PHP 8.0 was a major release, and it changed how PHP code looks:

  • Named arguments: htmlspecialchars($text, double_encode: false) skips the parameters you don't need (Parameters and Arguments).
  • match expression: a strict, value-returning switch (switch and match).
  • Nullsafe operator ?->: $user?->address?->city returns null instead of failing on a missing object (Null Coalescing, Ternary and Nullsafe Operators).
  • Constructor property promotion: declare and assign properties in the constructor signature (Constructors and Destructors).
  • Union types int|string, plus the mixed and static return types (Type Declarations).
  • Attributes #[...], structured metadata that replaced docblock annotations (Attributes).
  • throw as an expression, catches without a variable, str_contains(), str_starts_with(), str_ends_with(), and $object::class.
  • Saner string-to-number comparison: 0 == 'abc' is now false (Comparison Operators).
  • Most built-in functions now throw TypeError and ValueError instead of returning null with a warning. The JIT compiler arrived too (Performance and OPcache).
PHP PHP 8.0 features

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The invoice has no customer, so $invoice->customer?->email is NULL instead of an error. The last line shows the value of named arguments: htmlspecialchars() has two optional parameters before double_encode, and you didn't have to repeat their defaults. Because double_encode is off, the existing &amp; is left alone while <b> becomes &lt;b&gt;.

PHP 8.1 (November 2021)

  • Enums, pure and backed, with methods and interfaces (Class Constants and Enums).
  • Readonly properties that can be set once (Readonly Properties and Immutable Objects).
  • First-class callable syntax strlen(...) creates a closure from any function or method (Anonymous Functions and Closures).
  • new in initializers: public function __construct(private Logger $logger = new NullLogger()).
  • Pure intersection types Countable&Iterator and the never return type.
  • Fibers, the foundation for async libraries (Fibers and Asynchronous PHP).
  • array_is_list(), array unpacking with string keys, final class constants, and the explicit octal prefix 0o17.
PHP PHP 8.1 features

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

tryFrom() returns null for an unknown value, while from() would throw. Assigning to a readonly property after construction throws an Error with the message Cannot modify readonly property Order::$id.

PHP 8.2 (December 2022)

  • Readonly classes: readonly class Money { ... } makes every property readonly.
  • DNF types combine unions and intersections: (Countable&Traversable)|null.
  • null, false and true as standalone types.
  • The Random extension: Random\Randomizer with pluggable engines, including seedable ones for reproducible results (Hashing, Encryption and Random Numbers).
  • Constants in traits (Traits) and the #[\SensitiveParameter] attribute, which hides a value (like a password) from stack traces.
  • Deprecated: dynamic properties. Assigning a property that the class didn't declare now raises a deprecation, except on stdClass and classes marked #[\AllowDynamicProperties].
PHP PHP 8.2 features

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The seeded Mt19937(42) engine produces the same numbers on every run, which makes tests reproducible. For security-sensitive values, use the default engine (new Random\Randomizer()), which is cryptographically secure. Notice also new Money(...)->add(...) without extra parentheses, a PHP 8.4 feature you'll meet below.

PHP 8.3 (November 2023)

  • Typed class constants: const string PREFIX = 'inv-'; (Class Constants and Enums).
  • The #[\Override] attribute makes PHP check that a method really overrides a parent method (Inheritance).
  • Dynamic class constant fetch: Config::{$name} instead of constant(Config::class . '::' . $name).
  • json_validate() checks JSON without decoding it (JSON).
  • mb_str_pad(), Randomizer::getBytesFromString(), readonly properties can be reinitialized inside __clone(), and str_increment() / str_decrement() alongside a deprecation of ++ on non-alphanumeric strings (all non-numeric strings follow in 8.5).
PHP PHP 8.3 features

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

If you renamed Shape::area() to surface(), the #[\Override] attribute would turn the silent bug into a fatal error, because Square::area() would no longer override anything. str_increment('Az') gives Ba, the same "carry" logic as spreadsheet column names.

PHP 8.4 (November 2024)

  • Property hooks: get and set logic attached directly to a property, no getter/setter boilerplate (Property Hooks and Asymmetric Visibility).
  • Asymmetric visibility: public private(set) int $count is readable everywhere but writable only inside the class.
  • new without parentheses: new Request()->withHeader(...).
  • array_find(), array_find_key(), array_any() and array_all() (array_map, array_filter and array_reduce).
  • #[\Deprecated] for your own functions and methods, lazy objects in Reflection, the HTML5 parser Dom\HTMLDocument (XML), mb_trim(), the RoundingMode enum for round(), an object API for BCMath (BcMath\Number), and driver-specific PDO classes like Pdo\Sqlite (PDO Basics).
  • Deprecated: implicitly nullable parameters. function f(int $x = null) must become function f(?int $x = null).
PHP PHP 8.4 features

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The set hook validates every assignment, including the one in the constructor; the virtual fahrenheit property is computed on each read. Writing $t->changes from outside throws Cannot modify private(set) property Temperature::$changes from global scope. array_find() returns the first match, 48. RoundingMode::HalfEven rounds 2.5 to the nearest even number, 2, and BCMath's Number objects add 0.1 + 0.2 exactly as 0.3, which floats can't do.

PHP 8.5 (November 2025)

  • The pipe operator |> passes a value through a chain of single-argument callables from left to right (Bitwise, String, Array and Pipe Operators).
  • clone with: clone($object, ['property' => $newValue]) makes "wither" methods on readonly objects one line (Readonly Properties and Immutable Objects).
  • #[\NoDiscard] warns when a caller ignores a return value that matters; cast to (void) to ignore it on purpose (Using Built-in Functions).
  • array_first() and array_last() return the first and last values (or null for an empty array).
  • The URI extension: Uri\Rfc3986\Uri and Uri\WhatWg\Url parse and normalize URLs by the standards, replacing the quirky parse_url() for new code.
  • Closures and first-class callables in constant expressions, final on promoted properties, attributes on global constants, asymmetric visibility for static properties, and stack traces for fatal errors.
PHP PHP 8.5 features

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The pipe chain reads top to bottom, like a recipe: trim, lowercase, replace runs of other characters with -, then trim stray dashes, giving hello-world-php-8-5. Arrow functions in a pipe must be wrapped in parentheses. clone with copies the readonly object and changes only the listed property. It assigns with normal visibility rules, and readonly properties can only be written from inside their class, which is why the clone() calls live in "wither" methods; calling clone($dark, ['fontSize' => 20]) from outside the class throws an Error. If you wrote $dark->withLargerFont(); without using the result, PHP would print a warning, because the method is marked #[\NoDiscard]; (void) $dark->withLargerFont(); silences it on purpose. Finally, the URI parser splits the address into its parts and returns the host normalized to lowercase: shop.example.com | /cart | item=42.

Deprecations you'll meet when upgrading

A deprecation is a warning that a feature will be removed in a future major version. Your code still works, but the log fills with Deprecated: messages, and the next major version will break it. These are the ones that show up most in real code bases:

Version Deprecated Write instead
8.1 Passing null to non-nullable built-in parameters, e.g. strlen(null) strlen($value ?? '')
8.1 Serializable interface without __serialize() __serialize() / __unserialize()
8.2 Dynamic properties Declare the property, or #[\AllowDynamicProperties]
8.2 "${var}" string interpolation "{$var}"
8.3 ++ on non-alphanumeric strings like 'a-' str_increment()
8.5 ++ on any non-numeric string like 'a' str_increment()
8.4 Implicitly nullable parameters int $x = null ?int $x = null
8.4 E_STRICT constant, trigger_error() with E_USER_ERROR Exceptions
8.5 Backtick operator `ls` shell_exec() (or better, avoid it)
8.5 Non-canonical casts (integer), (boolean), (double) (int), (bool), (float)
8.5 null as an array key, $array[null] $array['']

The editor shows deprecations the same way a development server does:

PHP Deprecation messages in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This example raises deprecations on purpose. PHP reports the non-canonical cast (line 11) and the implicitly nullable $percent (line 4) while it compiles the file, before anything runs, and the dynamic property (line 10) when that line executes. The script still prints 30 x 3. Fix all three (declare public string $name;, write ?float, use (int)) and the warnings disappear.

An upgrade checklist

Upgrading one minor version at a time is usually painless if you follow a routine:

  1. Read the migration guide for the target version in the PHP manual. It lists every backward-incompatible change and deprecation.
  2. Run your tests on the new version first, locally or in CI (Testing PHP Code). Run them with error_reporting=E_ALL so deprecations show up.
  3. Fix deprecations before they become errors. Tools do much of this automatically: Rector rewrites code to newer syntax (for example adding ? to nullable parameters), and PHPStan or Psalm catch type problems.
  4. Update dependencies with composer update and check that each package supports the new version. The config.platform.php setting in composer.json makes Composer resolve packages for your production PHP version, not the one on your laptop.
  5. Deploy to staging, then production, and keep an eye on the error log for a few days (Deploying PHP Applications).

Make a habit of trying each new release's features in small places first: an enum instead of string constants, a readonly class for a value object, match instead of a long switch. Modern syntax is easier to read, and static analysers understand it better.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which release introduced enums and readonly properties?

    Enums, readonly properties, first-class callables, never and fibers all arrived in PHP 8.1. Readonly classes followed in 8.2.
  2. 2. What does ' Hi There ' |> trim(...) |> strtoupper(...) evaluate to in PHP 8.5?

    The pipe passes the value left to right, first to trim() and then to strtoupper(), giving 'HI THERE'. Only arrow functions need parentheses in a pipe.
  3. 3. PHP 8.4 reports Implicitly marking parameter $limit as nullable is deprecated. What is the fix for function page(int $limit = null)?

    A null default no longer makes the type nullable implicitly. Write the nullable type explicitly with ?int (or int|null).
  4. 4. What does the #[\Override] attribute (PHP 8.3) do?

    The attribute is a promise checked by PHP: if the parent method is renamed or removed, the class no longer compiles, instead of silently creating a new unrelated method.
  5. 5. How long is a PHP minor version (like 8.3) supported in total?

    Each version gets two years of bug fixes and two more years of security fixes. After four years it reaches end of life.

Summary

  • PHP releases a new minor version every November; each is supported for two years of bug fixes plus two years of security fixes. Upgrade about once a year.
  • 8.0: named arguments, match, ?->, constructor promotion, union types, attributes, str_contains(), saner comparisons, the JIT.
  • 8.1: enums, readonly properties, strlen(...) callables, new in initializers, never, intersection types, fibers.
  • 8.2: readonly classes, DNF types, true/false/null types, Random\Randomizer; dynamic properties deprecated.
  • 8.3: typed class constants, #[\Override], Class::{$name}, json_validate(), str_increment().
  • 8.4: property hooks, asymmetric visibility, new Foo()->bar(), array_find()/array_any()/array_all(), #[\Deprecated], Dom\HTMLDocument; implicit nullable parameters deprecated.
  • 8.5: the pipe operator |>, clone($obj, [...]), #[\NoDiscard], array_first()/array_last(), the URI extension; backticks and non-canonical casts deprecated.
  • Upgrade with tests, fix deprecations early (Rector and PHPStan help), update Composer dependencies, and watch your logs after deploying.

Next: Coding Standards and PSRs