Outsource Laravel Development Partner - $3200/Month | Bacancy

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.

image
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech
Bacancy logo

Bacancy

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

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
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
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

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

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant 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

The latest

View all →
New Colors Added in Tailwind CSS v4.2 image

New Colors Added in Tailwind CSS v4.2

Read article
Factory makeMany() Method in Laravel 12.52.0 image

Factory makeMany() Method in Laravel 12.52.0

Read article
Laravel Adds an Official Svelte + Inertia Starter Kit image

Laravel Adds an Official Svelte + Inertia Starter Kit

Read article
MongoDB Vector Search in Laravel: Finding the Unqueryable image

MongoDB Vector Search in Laravel: Finding the Unqueryable

Read article
Laravel Cloud Adds “Markdown for Agents” to Serve AI-Friendly Content image

Laravel Cloud Adds “Markdown for Agents” to Serve AI-Friendly Content

Read article
Laravel Releases Nightwatch MCP Server for Claude Code and AI Agents image

Laravel Releases Nightwatch MCP Server for Claude Code and AI Agents

Read article