PHP 8 features by version
suggest changePHP 8.0 came out in November 2020, and a new minor version has been released every November since then. Each one added a lot of syntax and functions, so "PHP 8" code can look very different depending on which 8.x it targets.
This article is a map of those releases. For each version from 8.0 to 8.5 you get:
- a table of the headline features, each with a one-line example and a link to the article in this book that covers it
- a short runnable program that uses several of them together
- the deprecations and backward-incompatible changes that are most likely to affect existing code
Use it to find out whether a feature is available on the PHP version you deploy to, or to see what you get by upgrading.
All examples were run with PHP 8.5. Each program needs at least the version its section is about. In the outputs, file paths are shortened to the file name.
Related topics: Getting started with PHP has the history of versions up to PHP 7.
Checking the PHP version
PHP gives you the version as a string and as an integer. PHP_VERSION_ID is major * 10000 + minor * 100 + patch, so it is easy to compare:
<?php
echo PHP_VERSION, "\n";
echo PHP_MAJOR_VERSION, '.', PHP_MINOR_VERSION, "\n";
echo PHP_VERSION_ID, "\n";
if (PHP_VERSION_ID >= 80400) {
echo "property hooks and array_find() are available\n";
}
var_dump(version_compare(PHP_VERSION, '8.5.0', '>='));
var_dump(function_exists('array_first'));
Output:
8.5.11
8.5
80511
property hooks and array_find() are available
bool(true)
bool(true)
A version check can't protect new syntax. A file that uses |> or property hooks fails to compile on older PHP before any if runs. A runtime check only helps for new functions and classes. To require a minimum version for a whole project, put it in composer.json ("require": {"php": ">=8.3"}) so Composer refuses to install on older versions.
Release and support dates
Each version gets two years of bug fixes ("active support") and then two years of security fixes only. Since 2024 support ends on December 31 of the final year.
| Version | Released | Active support until | Security fixes until |
|---|---|---|---|
| 8.0 | 2020-11-26 | 2022-11-26 | 2023-11-26 |
| 8.1 | 2021-11-25 | 2023-11-25 | 2025-12-31 |
| 8.2 | 2022-12-08 | 2024-12-31 | 2026-12-31 |
| 8.3 | 2023-11-23 | 2025-12-31 | 2027-12-31 |
| 8.4 | 2024-11-21 | 2026-12-31 | 2028-12-31 |
| 8.5 | 2025-11-20 | 2027-12-31 | 2029-12-31 |
PHP 8.0 and 8.1 no longer get any fixes. The current list is on the supported versions page.
PHP 8.0
The biggest release of the series. It added the JIT compiler and a lot of syntax that is now used everywhere.
| Feature | Example | Read more |
|---|---|---|
| Union types | int|string $id |
Union, intersection and DNF types |
mixed and static return types |
function with(): static |
mixed, never, static, null, false and true types |
match expression |
match ($x) { 1, 2 => 'low', default => 'high' } |
Pattern matching |
| Nullsafe operator | $user?->getAddress()?->city |
null, isset, and ?? |
| Named arguments | htmlspecialchars($s, double_encode: false) |
Named and optional parameters |
| Constructor property promotion | __construct(private int $id) |
Properties |
| Attributes | #[Route('/home')] |
Attributes |
throw as an expression |
$x ?? throw new Exception() |
Throw expressions and non-capturing catches |
| Catch without a variable | catch (TypeError) { ... } |
Throw expressions and non-capturing catches |
str_contains, str_starts_with, str_ends_with |
str_contains($s, 'php') |
Modern string functions |
Stringable interface |
added automatically to classes with __toString() |
Polymorphism |
WeakMap |
$cache = new WeakMap() |
Memory and garbage collection |
get_debug_type() |
get_debug_type(1.5) gives float |
Union, intersection and DNF types |
::class on objects |
$obj::class |
|
| Trailing comma in parameter lists | function f($a, $b,) |
Several of them in one program:
<?php
final class Money
{
public function __construct( // constructor property promotion
public int $cents = 0,
public string $currency = 'USD', // trailing comma in parameter list
) {}
public function __toString(): string // implements Stringable automatically
{
return sprintf('%.2f %s', $this->cents / 100, $this->currency);
}
}
function describe(int|float|string $v): string // union type
{
return match (true) { // match expression
is_int($v) => "int $v",
is_float($v) => "float $v",
default => "string '$v'",
};
}
$m = new Money(currency: 'EUR', cents: 1999); // named arguments
echo $m, "\n";
var_dump($m instanceof Stringable);
echo $m::class, "\n"; // ::class on an object
echo describe(3), ' / ', describe(1.5), ' / ', describe('x'), "\n";
$user = null;
var_dump($user?->getAddress()?->city); // nullsafe operator
var_dump(str_contains('haystack', 'st'), str_starts_with('haystack', 'hay'));
function requireName(array $input): string
{
return $input['name'] ?? throw new InvalidArgumentException('name required');
}
try {
requireName([]);
} catch (InvalidArgumentException) { // catch without a variable
echo "missing name\n";
}
echo get_debug_type(1.5), ' ', get_debug_type($m), "\n";
Output:
19.99 EUR
bool(true)
Money
int 3 / float 1.5 / string 'x'
NULL
bool(true)
bool(true)
missing name
float Money
Breaking changes in 8.0
Two changes break old code most often.
String to number comparison. Comparing a number with a non-numeric string now compares them as strings. In PHP 7, 0 == 'foo' was true because 'foo' was converted to 0. See Comparison Operators and Type Comparison.
Internal functions throw. Passing a wrong type or an invalid value to a built-in function throws TypeError or ValueError instead of printing a warning and returning null or false:
<?php
var_dump(0 == 'foo'); // true in PHP 7, false in PHP 8
var_dump(0 == ''); // true in PHP 7, false in PHP 8
var_dump('1' == '01'); // numeric strings still compare as numbers
var_dump(42 == ' 42'); // leading whitespace is allowed
try {
strlen([]);
} catch (TypeError $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}
try {
array_chunk([1, 2, 3], 0);
} catch (ValueError $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}
Output:
bool(false)
bool(false)
bool(true)
bool(true)
TypeError: strlen(): Argument #1 ($string) must be of type string, array given
ValueError: array_chunk(): Argument #2 ($length) must be greater than 0
Other notable changes: many warnings became Error exceptions (for example reading a property of a non-object), the @ operator no longer hides fatal errors, a required parameter after an optional one is deprecated, and resources such as curl and GdImage handles became objects.
PHP 8.1
Enums, readonly properties and Fibers.
| Feature | Example | Read more |
|---|---|---|
| Enums | enum Status: string { case Draft = 'draft'; } |
Enums |
| Readonly properties | public readonly string $title |
Immutability, Properties |
| First-class callable syntax | strlen(...), $obj->method(...) |
First-class callable syntax |
new in initializers |
Logger $l = new NullLogger() |
Named and optional parameters, Typed class constants and constant expressions |
| Pure intersection types | Countable&Iterator $it |
Union, intersection and DNF types |
never return type |
function fail(): never |
mixed, never, static, null, false and true types |
| Fibers | Fiber::suspend($value) |
Fibers |
array_is_list() |
array_is_list([1, 2]) |
Finding elements with array_find, array_any and array_all |
final class constants |
final public const X = 1; |
Typed class constants and constant expressions |
| Array unpacking with string keys | [...$defaults, 'size' => 'L'] |
Merge or concatenate arrays |
| Explicit octal notation | 0o17 |
<?php
enum Status: string // backed enum
{
case Draft = 'draft';
case Published = 'published';
public function label(): string
{
return ucfirst($this->value);
}
}
final class Logger
{
public function log(string $msg): void { echo "[log] $msg\n"; }
}
final class Post
{
public function __construct(
public readonly string $title, // readonly property
public readonly Status $status = Status::Draft,
private Logger $logger = new Logger(), // new in initializer
) {}
public function publish(): never // never returns
{
$this->logger->log("publishing {$this->title}");
throw new LogicException('not implemented');
}
}
$post = new Post('Hello');
echo $post->status->label(), "\n";
echo Status::from('published')->name, "\n";
try {
$post->title = 'Changed';
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
$upper = strtoupper(...); // first-class callable
echo implode(',', array_map($upper, ['a', 'b'])), "\n";
var_dump(array_is_list([1, 2]), array_is_list([1 => 'a']));
$defaults = ['color' => 'red', 'size' => 'M'];
echo json_encode([...$defaults, 'size' => 'L']), "\n"; // unpacking string keys
echo 0o17, "\n"; // explicit octal
$fiber = new Fiber(function (string $x): string {
$y = Fiber::suspend("got $x");
return "resumed with $y";
});
echo $fiber->start('a'), "\n";
$fiber->resume('b');
echo $fiber->getReturn(), "\n";
Output:
Draft
Published
Cannot modify readonly property Post::$title
A,B
bool(true)
bool(false)
{"color":"red","size":"L"}
15
got a
resumed with b
Deprecations in 8.1
The one you will hit most: passing null to a non-nullable parameter of a built-in function. It used to be silently converted to '' or 0:
<?php
$name = null;
echo strlen($name), "\n"; // null passed to a non-nullable internal parameter
echo str_replace('a', 'b', null), "|\n";
Output:
Deprecated: strlen(): Passing null to parameter #1 ($string) of type string is deprecated in bc81.php on line 3
0
Deprecated: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated in bc81.php on line 4
|
The fix is to handle null before the call, for example strlen($name ?? ''). Also deprecated in 8.1: implementing Serializable without __serialize()/__unserialize(), auto-creating an array from false ($x = false; $x[] = 1;), and overriding a built-in method without a compatible return type (add the type or #[\ReturnTypeWillChange]). Writing to the whole $GLOBALS array is no longer allowed.
PHP 8.2
Readonly classes, more precise types and the Random extension.
| Feature | Example | Read more |
|---|---|---|
| Readonly classes | readonly class Point { ... } |
Immutability |
| DNF types | (HasId&HasName)|null $item |
Union, intersection and DNF types |
null, false, true as standalone types |
function isValid(): true |
mixed, never, static, null, false and true types |
| Constants in traits | trait T { const VERSION = 2; } |
Traits |
| Enum properties in constant expressions | const D = Suit::Hearts->value; |
Enums |
| Random extension | new Random\Randomizer() |
Random numbers |
#[\SensitiveParameter] |
hides an argument in stack traces | Stack traces |
#[\AllowDynamicProperties] |
opts a class out of the dynamic property deprecation | Attributes |
<?php
readonly class Point // readonly class
{
public function __construct(public int $x, public int $y) {}
}
interface HasId { public function id(): int; }
interface HasName { public function name(): string; }
function show((HasId&HasName)|null $item): string // DNF type
{
return $item === null ? 'nothing' : $item->id() . ':' . $item->name();
}
function alwaysFalse(): false { return false; } // false/true/null standalone
trait Versioned
{
public const VERSION = 2; // constants in traits
}
final class Doc implements HasId, HasName
{
use Versioned;
public function id(): int { return 7; }
public function name(): string { return 'readme'; }
}
enum Suit: string
{
case Hearts = 'H';
const DEFAULT = self::Hearts->value; // enum property in const expression
}
echo show(new Doc()), ' / ', show(null), "\n";
echo Doc::VERSION, ' ', Suit::DEFAULT, "\n";
$rng = new Random\Randomizer(new Random\Engine\Xoshiro256StarStar(42));
echo $rng->getInt(1, 100), ' ', implode('', $rng->shuffleArray(['a', 'b', 'c'])), "\n";
function login(string $user, #[\SensitiveParameter] string $password): void
{
throw new RuntimeException('bad login');
}
try {
login('ann', 'hunter2');
} catch (RuntimeException $e) {
echo $e->getTraceAsString(), "\n";
}
Output:
7:readme / nothing
2 H
15 acb
#0 p82.php(47): login('ann', Object(SensitiveParameterValue))
#1 {main}
The seeded engine always gives the same numbers, which is useful in tests.
Deprecations in 8.2
Dynamic properties. Assigning a property that isn't declared on the class is deprecated. Declare the property, add #[\AllowDynamicProperties], or implement __get()/__set(). stdClass is not affected. See Properties.
${var} string interpolation. Use {$var} instead. See Strings.
<?php
class User {}
#[\AllowDynamicProperties]
class LegacyUser {}
$u = new User();
$u->nickname = 'ann'; // dynamic property: deprecated
$l = new LegacyUser();
$l->nickname = 'bob'; // allowed by the attribute
$name = 'Ann';
echo "Hello ${name}\n"; // ${} interpolation: deprecated
echo "Hello {$name}\n"; // fine
Output:
Deprecated: Using ${var} in strings is deprecated, use {$var} instead in bc82.php on line 14
Deprecated: Creation of dynamic property User::$nickname is deprecated in bc82.php on line 8
Hello Ann
Hello Ann
The ${} warning comes first because the compiler emits it before the script runs. Also deprecated in 8.2: utf8_encode() and utf8_decode() (use mb_convert_encoding()), and callables that only work through call_user_func() such as "self::method".
PHP 8.3
A smaller release, mostly about constants, attributes and new functions.
| Feature | Example | Read more |
|---|---|---|
| Typed class constants | const string PREFIX = 'item-'; |
Typed class constants and constant expressions |
| Dynamic class constant fetch | Item::{$name} |
Typed class constants and constant expressions |
#[\Override] |
fails if the method doesn't override anything | Overriding, Attributes |
Readonly properties can be re-initialized in __clone() |
deep copies of readonly objects | Immutability |
| Anonymous readonly classes | new readonly class { ... } |
Anonymous classes |
json_validate() |
json_validate($body) |
Validating JSON with json_validate |
str_increment(), str_decrement() |
str_increment('Az') gives Ba |
Modern string functions |
mb_str_pad() |
mb_str_pad('żółw', 6, '*') |
Modern string functions |
Randomizer::getBytesFromString(), getFloat() |
random tokens from an alphabet | Random numbers |
| Date exceptions | DateMalformedStringException |
Throw expressions and non-capturing catches |
<?php
interface HasLabel
{
const string PREFIX = 'item-'; // typed class constant
}
class Base
{
public function render(): string { return 'base'; }
}
final class Item extends Base implements HasLabel
{
const string DEFAULT_SIZE = 'M';
#[\Override] // must override a parent method
public function render(): string { return self::PREFIX . 'item'; }
}
$const = 'DEFAULT_SIZE';
echo Item::{$const}, "\n"; // dynamic class constant fetch
echo (new Item())->render(), "\n";
var_dump(json_validate('{"a": 1}'), json_validate('{a: 1}'));
echo str_increment('Az'), ' ', str_decrement('Ba'), "\n";
$rng = new Random\Randomizer(new Random\Engine\Xoshiro256StarStar(1));
echo $rng->getBytesFromString('abcdef0123456789', 8), "\n";
try {
new DateTimeImmutable('not a date');
} catch (DateMalformedStringException $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}
$obj = new readonly class(1) { // anonymous readonly class
public function __construct(public int $n) {}
};
echo $obj->n, "\n";
Output:
M
item-item
bool(true)
bool(false)
Ba Az
fa1979cd
DateMalformedStringException: Failed to parse time string (not a date) at position 0 (n): The timezone could not be found in the database
1
Deprecations in 8.3
PHP 8.3 started deprecating ++ and -- on strings that aren't numbers, with str_increment() and str_decrement() as the replacement. In PHP 8.5 the warning is raised for every non-numeric string, including plain alphanumeric ones like 'a9'. get_class() and get_parent_class() without an argument are deprecated too:
<?php
$s = 'a9';
$s++; // still works: 'b0'
echo $s, "\n";
$e = '';
$e++; // deprecated: increment on empty string
var_dump($e);
$x = 'a-';
$x++; // deprecated: non-alphanumeric string
var_dump($x);
class A { function name() { return get_class(); } }
echo (new A())->name(), "\n"; // get_class() without argument: deprecated
Output (PHP 8.5):
Deprecated: Increment on non-numeric string is deprecated, use str_increment() instead in bc83.php on line 3
b0
Deprecated: Increment on non-numeric string is deprecated, use str_increment() instead in bc83.php on line 7
string(1) "1"
Deprecated: Increment on non-numeric string is deprecated, use str_increment() instead in bc83.php on line 11
string(2) "a-"
Deprecated: Calling get_class() without arguments is deprecated in bc83.php on line 14
A
Use self::class or static::class instead of get_class(), and $obj::class instead of get_class($obj) if you prefer.
PHP 8.4
Property hooks and asymmetric visibility change how classes are written. This release also added lazy objects and a standards-compliant HTML5 parser.
| Feature | Example | Read more |
|---|---|---|
| Property hooks | public string $name { set => trim($value); } |
Property hooks |
| Asymmetric visibility | public private(set) int $count |
Properties, Immutability |
| Lazy objects | $r->newLazyGhost($init) |
Lazy objects, Composition and delegation |
new without parentheses |
new Foo()->bar() |
|
array_find(), array_find_key(), array_any(), array_all() |
array_find($users, fn($u) => $u->isAdmin()) |
Finding elements with array_find, array_any and array_all |
#[\Deprecated] |
marks your own functions as deprecated | Attributes |
Dom\HTMLDocument |
Dom\HTMLDocument::createFromString($html) |
Parsing HTML5 with Dom\HTMLDocument, Web scraping |
BcMath\Number |
new BcMath\Number('0.1') + '0.2' |
Math |
request_parse_body() |
form data for PUT and PATCH requests | Parsing PUT and PATCH bodies with request_parse_body |
mb_trim(), mb_ucfirst(), mb_lcfirst(), grapheme_str_split() |
mb_trim("\u{3000}text") |
Modern string functions |
RoundingMode enum for round() |
round(2.5, 0, RoundingMode::HalfEven) |
Math |
| Driver-specific PDO subclasses | PDO::connect() returns Pdo\Sqlite |
Driver-specific PDO classes |
<?php
final class Temperature
{
public float $celsius { // property hook
set(float $value) {
if ($value < -273.15) {
throw new ValueError('below absolute zero');
}
$this->celsius = $value;
}
}
public float $fahrenheit { // virtual property
get => $this->celsius * 9 / 5 + 32;
}
public private(set) int $changes = 0; // asymmetric visibility
public function __construct(float $celsius)
{
$this->celsius = $celsius;
}
public function warm(float $by): static
{
$this->celsius += $by;
$this->changes++;
return $this;
}
}
echo new Temperature(20)->warm(5)->fahrenheit, "\n"; // new without parentheses
$t = new Temperature(0);
try {
$t->changes = 10;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
$users = [['id' => 1, 'name' => 'Ann'], ['id' => 2, 'name' => 'Bob']];
echo array_find($users, fn($u) => $u['id'] === 2)['name'], "\n";
var_dump(array_any($users, fn($u) => $u['name'] === 'Ann'));
var_dump(array_all($users, fn($u) => $u['id'] > 0));
$doc = Dom\HTMLDocument::createFromString('<p class="x">Hi <b>there</b>', LIBXML_NOERROR);
echo $doc->querySelector('p.x')->textContent, "\n";
$total = new BcMath\Number('0.1') + new BcMath\Number('0.2');
echo $total, ' ', var_export($total == new BcMath\Number('0.3'), true), "\n";
#[\Deprecated(message: 'use newApi()', since: '2.0')]
function oldApi(): void {}
oldApi();
echo round(2.5, 0, RoundingMode::HalfEven), "\n";
Output:
77
Cannot modify private(set) property Temperature::$changes from global scope
Bob
bool(true)
bool(true)
Hi there
0.3 true
Deprecated: Function oldApi() is deprecated since 2.0, use newApi() in p84.php on line 54
2
Deprecations in 8.4
Implicitly nullable parameters. A parameter with a type and a null default, like array $opts = null, used to become nullable without saying so. Now you must write ?array $opts = null (or array|null). This affects a lot of older code. Tools like PHP-CS-Fixer (nullable_type_declaration_for_default_null_value) and Rector can fix it automatically. See Nullable type hints and Named and optional parameters.
trigger_error() with E_USER_ERROR. Throw an exception or call exit() instead.
<?php
function find(string $id, array $opts = null) {} // implicitly nullable: deprecated
function findOk(string $id, ?array $opts = null) {} // explicit: fine
trigger_error('stop', E_USER_ERROR); // deprecated
Output:
Deprecated: find(): Implicitly marking parameter $opts as nullable is deprecated, the explicit nullable type must be used instead in bc84.php on line 2
Deprecated: Passing E_USER_ERROR to trigger_error() is deprecated since 8.4, throw an exception or call exit with a string message instead in bc84.php on line 5
Fatal error: stop in bc84.php on line 5
Stack trace:
#0 bc84.php(5): trigger_error('stop', 256)
#1 {main}
Other 8.4 changes: the E_STRICT error level is gone and its constant is deprecated (see Setting error reporting and where to display them), using _ as a class name is deprecated, and exit() became a real function, so it can be passed as a callable and its argument is type-checked.
PHP 8.5
The pipe operator, clone with property overrides and a URL parser that follows the standards.
| Feature | Example | Read more |
|---|---|---|
| Pipe operator | $s |> trim(...) |> strtolower(...) |
The pipe operator |> |
clone with property overrides |
clone($this, ['debug' => true]) |
Immutability |
| Uri extension | Uri\WhatWg\Url::parse($s) |
Parsing and building URLs with the Uri extension |
#[\NoDiscard] and the (void) cast |
warns when a return value is ignored | #[\NoDiscard] and the (void) cast |
array_first(), array_last() |
array_first($items) |
Finding elements with array_find, array_any and array_all |
| Closures and first-class callables in constant expressions | const UPPER = strtoupper(...); |
Typed class constants and constant expressions |
| Casts in constant expressions, attributes on global constants | const N = (int) '1'; |
Typed class constants and constant expressions |
| Asymmetric visibility for static properties | public private(set) static int $count |
Static members |
#[\Override] on properties |
checks that a property exists in the parent | #[\NoDiscard] and the (void) cast |
| Backtraces for fatal errors | Fatal error: ... Stack trace: #0 ... |
Stack traces |
get_error_handler(), get_exception_handler() |
read the current handler | Throw expressions and non-capturing catches |
<?php
$slug = ' Hello PHP World '
|> trim(...)
|> strtolower(...)
|> (fn($s) => str_replace(' ', '-', $s)); // pipe operator
echo $slug, "\n";
final readonly class Config
{
public function __construct(public string $env, public bool $debug) {}
public function withDebug(bool $debug): static
{
return clone($this, ['debug' => $debug]); // clone with
}
}
$prod = new Config('prod', false);
var_dump($prod->withDebug(true)->debug);
echo array_first(['a' => 1, 'b' => 2]), ' ', array_last([]) ?? 'none', "\n";
$url = Uri\WhatWg\Url::parse('https://example.com/docs/../a?q=1');
echo $url->getAsciiHost(), ' ', $url->getPath(), "\n";
echo $url->resolve('b/c')->toAsciiString(), "\n";
#[\NoDiscard('the copy is the result')]
function withTitle(array $page, string $title): array
{
return [...$page, 'title' => $title];
}
withTitle([], 'Home'); // warning: result unused
(void) withTitle([], 'Home'); // explicitly discarded
final class Formatter
{
public const UPPER = strtoupper(...); // first-class callable in const expr
}
echo (Formatter::UPPER)('ok'), "\n";
class Counter
{
public private(set) static int $count = 0; // static asymmetric visibility
public static function inc(): void { self::$count++; }
}
Counter::inc();
echo Counter::$count, "\n";
set_error_handler(fn() => true);
var_dump(get_error_handler() instanceof Closure);
restore_error_handler();
Output:
hello-php-world
bool(true)
1 none
example.com /a
https://example.com/b/c
Warning: The return value of function withTitle() should either be used or intentionally ignored by casting it as (void), the copy is the result in p85.php on line 31
OK
1
bool(true)
Note that Url::parse() already removed the docs/.. segment from the path.
Deprecations in 8.5
Most 8.5 deprecations remove old alternative spellings:
<?php
$n = (integer) '42'; // non-canonical cast name: use (int)
$b = (boolean) 1; // use (bool)
$out = `echo hi`; // backtick operator: use shell_exec()
$map = ['' => 'empty key'];
echo $map[null], "\n"; // null as an array offset
switch ($n) {
case 42; // case ended with a semicolon
echo "forty-two\n";
}
Output:
Deprecated: Non-canonical cast (integer) is deprecated, use the (int) cast instead in bc85.php on line 2
Deprecated: Non-canonical cast (boolean) is deprecated, use the (bool) cast instead in bc85.php on line 3
Deprecated: The backtick (`) operator is deprecated, use shell_exec() instead in bc85.php on line 5
Deprecated: Case statements followed by a semicolon (;) are deprecated, use a colon (:) instead in bc85.php on line 11
Deprecated: Using null as an array offset is deprecated, use an empty string instead in bc85.php on line 8
empty key
forty-two
(double) and (binary) are deprecated the same way. Passing null as the key to array_key_exists() is also deprecated. The Execution Operator article describes the backtick operator.
Deprecations at a glance
A deprecation is only a warning, but the feature is usually removed in the next major version (PHP 9). Fixing them early makes that upgrade easy.
| Version | Deprecated or changed | Replacement |
|---|---|---|
| 8.0 | 0 == 'foo' is now false |
compare with === and convert explicitly |
| 8.0 | built-in functions throw TypeError/ValueError |
validate input or catch the error |
| 8.0 | required parameter after an optional one | reorder the parameters |
| 8.1 | null to non-nullable internal parameters |
$x ?? '' before the call |
| 8.1 | Serializable without __serialize() |
__serialize()/__unserialize() |
| 8.2 | dynamic properties | declare them, or #[\AllowDynamicProperties] |
| 8.2 | "${var}" interpolation |
"{$var}" |
| 8.2 | utf8_encode(), utf8_decode() |
mb_convert_encoding() |
| 8.3 | ++/-- on non-numeric strings |
str_increment(), str_decrement() |
| 8.3 | get_class() without an argument |
self::class, static::class |
| 8.4 | implicitly nullable parameters | ?Type $x = null |
| 8.4 | trigger_error(..., E_USER_ERROR) |
throw an exception |
| 8.4 | E_STRICT |
remove it from error_reporting() calls |
| 8.5 | backtick operator | shell_exec() |
| 8.5 | (integer), (boolean), (double), (binary) |
(int), (bool), (float), (string) |
| 8.5 | null as an array offset |
'' |
| 8.5 | case 1; |
case 1: |
To see all deprecations while you test, use error_reporting(E_ALL) and log or display errors. In production, keep E_DEPRECATED in the log so you find the remaining cases before the next upgrade.
Supporting several PHP versions
Libraries often have to run on more than one PHP version. Some ways to deal with that:
- New functions can be polyfilled. The
symfony/polyfill-php80tosymfony/polyfill-php85packages define functions likestr_contains(),array_is_list(),json_validate(),array_find()andarray_first()on older versions. - New syntax can't be polyfilled. Enums, readonly, property hooks,
|>andclonewith arguments need the version that introduced them. Set the minimum incomposer.jsonand run CI on every version you support. - Guard optional features at runtime with
function_exists(),class_exists()orPHP_VERSION_ID, as shown at the top of this article. - Automate upgrades. Rector rewrites code to use newer syntax (for example promoted properties or
match), and static analyzers like PHPStan and Psalm report deprecated calls for a targetphpVersion.
Summary
- 8.0: union types,
match, nullsafe?->, named arguments, constructor promotion, attributes,throwexpressions,str_contains(). Non-numeric strings no longer compare equal to0, and built-in functions throw on bad arguments. - 8.1: enums, readonly properties,
strlen(...)callables,newin initializers, intersection types,never, Fibers. Passingnullto built-in functions is deprecated. - 8.2: readonly classes, DNF types,
true/false/nulltypes, the Random extension,#[\SensitiveParameter]. Dynamic properties are deprecated. - 8.3: typed class constants,
#[\Override],json_validate(),str_increment(), Date exceptions. - 8.4: property hooks, asymmetric visibility, lazy objects,
array_find(),Dom\HTMLDocument,BcMath\Number,request_parse_body(). Implicitly nullable parameters are deprecated. - 8.5: the pipe operator,
clonewith overrides, the Uri extension,#[\NoDiscard],array_first()/array_last(), closures in constant expressions. Backticks and long cast names are deprecated.