PHP 8.3 is released with typed class constants, a json_validate function, and more

Published on by

PHP 8.3 is released with typed class constants, a json_validate function, and more image

The PHP team has released PHP 8.3 today with typed class constants, a json_validate() function, dynamically fetching a class constant, the #[Override] attribute, and more:

Typed Class Constants

In PHP 8.2, it was still not possible to declare constant (const) types, which can lead to confusion or implications about the type you're working with:

interface I {
const TEST = "Test"; // We may naively assume that the TEST constant is always a string
}
 
class Foo implements I {
const TEST = []; // But it may be an array...
}
 
class Bar extends Foo {
const TEST = null; // Or null
}

Here's an example of how typed constants look in PHP 8.3:

interface I {
const string TEST = E::TEST; // I::TEST is a string as well
}
 
class Foo implements I {
use T;
 
const string TEST = E::TEST; // Foo::TEST must also be a string
}
 
class Bar extends Foo {
const string TEST = "Test2"; // Bar::TEST must also be a string, but the value can change
}
 
// Error example
 
// Fatal error: Cannot use array as value for class constant
// Foo::PHP of type string
class Buzz implements I {
const string PHP = [];
}

The json_validate() function

To validate JSON in PHP, you would need to either configure the JSON_THROW_ON_ERROR flag, use json_last_error, or even just check for null on a json_decode() call:

json_decode(json: '{"foo": "bar}', flags: JSON_THROW_ON_ERROR);
 
// JsonException Control character error, possibly incorrectly encoded.

As of PHP 8.3, you can also validate JSON using the json_validate() function:

// Valid
json_validate('{"framework": "Laravel"}'); // true
 
// Invalid
json_validate('{"framework": "Laravel}'); // false
 
json_last_error_msg(); // Control character error, possibly incorrectly encoded
json_last_error(); // 3

Dynamic class constant fetch

In PHP >= 8.2, dynamically fetching a class constant value was only possible using the constant() function. The following would result in a syntax error:

class Framework {
const NAME = 'Laravel';
}
 
$name = 'NAME';
 
// You could achieve this with the constant() function
constant(Framework::class . '::' . $name); // Laravel
 
// This following is a syntax error in >=v8.2.0
echo Framework::{$name};
// ParseError syntax error, unexpected token ";", expecting "(".

As of PHP 8.3, you can now access constants dynamically from a class,

class Framework {
const NAME = 'Laravel';
}
 
$name = 'NAME';
 
// Syntax error in <= v8.2.0
echo Framework::{$name}; // Laravel

Fallback value for environment variables in INI files

One of my favorite additions to PHP 8.3 is providing a default value when using environment variables to define INI settings. This will simplify Docker defaults without having to specify the defaults as ENV blocks in a Dockerfile. I am sure there are plenty of use cases out there that will be simplified by this.

Let's say, for example, that you want to allow a DRUPAL_FPM_PORT ENV value to configure an INI value for the www FPM pool:

error_log = syslog
daemonize = false
 
[www]
listen = localhost:${DRUPAL_FPM_PORT}

The DRUPAL_FPM_PORT must be defined, and no default was possible! Now, you can do the following, which should feel familiar to a bash/shell script:

[www]
listen = localhost:${DRUPAL_FPM_PORT:-9000}

Imagine shipping an xdebug.ini file as part of your Dockerfile for development with sensible defaults yet allowing developers to override values they see fit.

Randomizer Additions

PHP 8.3 includes Randomizer Additions, including a new getBytesFromString() method, which is convenient to get random bytes from a source string:

$randomizer = new \Random\Randomizer();
 
printf(
"%s.example.com",
$randomizer->getBytesFromString('abcdefghijklmnopqrstuvwxyz0123456789', 16)
);
 
// 3zsw04eiubcf82jd.example.com
 
 
// Generate a random code for multi-factor authentication
$randomizer = new \Random\Randomizer(new \Random\Engine\Secure());
 
echo implode('-', str_split($randomizer->getBytesFromString('0123456789', 20), 5));
 
// 11551-80418-27047-42075

Learn more

To get up to speed on these new features, check out the PHP 8.3.0 Release Announcement page for examples before/after PHP 8.3. Be sure to check out the deprecations and backward compatibility breaks.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Visit Paragraph
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
Bacancy - Staff Augmentation logo

Bacancy - Staff Augmentation

Leave your web app development hustles to the leading IT Staff Augmentation Service Providers. Choose from an extensive pool of 1050+ developers and give yourself the sigh of success you deserve with Bacancy. Get In Touch Today!

Bacancy - Staff Augmentation
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Add Kanban Boards to Your Laravel App in Seconds image

Add Kanban Boards to Your Laravel App in Seconds

Read article
October CMS v3.6 Ships Today, Full of New Features image

October CMS v3.6 Ships Today, Full of New Features

Read article
Laracon EU Videos are now out image

Laracon EU Videos are now out

Read article
Use Google's Gemini AI in Laravel image

Use Google's Gemini AI in Laravel

Read article
PhpStorm is getting a brand new terminal image

PhpStorm is getting a brand new terminal

Read article
Six Essential Plugins for Visual Studio Code image

Six Essential Plugins for Visual Studio Code

Read article