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.

Filed in:
Cube

Laravel Newsletter

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

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
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

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

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Add Comments to your Laravel Application with the Commenter Package image

Add Comments to your Laravel Application with the Commenter Package

Read article
Laravel Advanced String Package image

Laravel Advanced String Package

Read article
Take the Annual State of Laravel 2024 Survey image

Take the Annual State of Laravel 2024 Survey

Read article
Upload Files Using Filepond in Livewire Components image

Upload Files Using Filepond in Livewire Components

Read article
The Best Laravel Tutorials and Resources for Developers image

The Best Laravel Tutorials and Resources for Developers

Read article
Introducing Built with Laravel image

Introducing Built with Laravel

Read article