PHP 8.3 was released in November 2023. These features need PHP 8.3 or newer. On an older PHP version they are parse errors or missing functions, and this server’s examples cannot run them. The code below follows the official release notes at php.net/releases/8.3.
Typed class constants
Class constants can now declare a type.
<?php
interface I
{
const string PHP = "PHP 8.3";
}
class Foo implements I
{
const string PHP = "PHP 8.3"; // must match the declared type
}
A child or implementing class that uses a different type gets an error. See Class Constants.
Dynamic class constant fetch
You can read a constant whose name is in a variable, with ::{$name}.
<?php
class Foo
{
const PHP = "PHP 8.3";
}
$name = "PHP";
echo Foo::{$name}; // PHP 8.3
Before 8.3, you needed constant(Foo::class . "::$name").
The #[\Override] attribute
Marks a method as intentionally overriding a parent method. PHP checks that the parent method exists, so typos and renames are caught.
<?php
class Parent1
{
protected function tearDown(): void {}
}
class Child extends Parent1
{
#[\Override]
protected function taerDown(): void {} // Fatal error: no matching parent method
}
See Method Overriding.
json_validate()
Checks whether a string is valid JSON without decoding it, which is faster and uses less memory than json_decode() when you only need a yes or no.
<?php
var_dump(json_validate('{ "test": { "foo": "bar" } }')); // true
var_dump(json_validate('{ bad')); // false
On PHP 8.2 and earlier, the function does not exist. A fallback:
<?php
function isJson(string $text): bool
{
if (function_exists("json_validate")) {
return json_validate($text);
}
json_decode($text);
return json_last_error() === JSON_ERROR_NONE;
}
var_dump(isJson('{"a":1}'));
var_dump(isJson("{oops"));
bool(true)
bool(false)
Readonly properties and cloning
PHP 8.3 lets __clone() re-initialise readonly properties, so you can deep-clone objects held in readonly properties.
<?php
class Foo
{
public function __construct(public readonly Bar $bar) {}
public function __clone(): void
{
$this->bar = clone $this->bar; // allowed since 8.3
}
}
Random and string helpers
\Random\Randomizer::getBytesFromString()builds a random string from characters you choose.\Random\Randomizer::getFloat()andnextFloat()produce unbiased random floats.str_increment()andstr_decrement()step through alphanumeric strings.mb_str_pad()pads multibyte strings.
Other changes
- Anonymous classes can be
readonly. php -lcan check several files at once.- New DOM and Intl methods, and more precise errors for date functions.
Should you use it?
Use PHP 8.3 or newer if your host allows it. Do not use these features in code that must also run on PHP 8.2 or 8.1.