ylliX - Online Advertising Network What’s New in PHP 8.3? - Yet Another Programmer's Blog

What’s New in PHP 8.3?

Introducing json_validate: An Advancement in JSON Handling
An impressive inclusion is the json_validate function.


Coming after json_decode, this fresh function provides a more efficient approach to validating JSON strings, improving performance and streamlining implementations.

var_dump(json_validate('{ "test": { "foo": "bar" } }'));
var_dump(json_validate('{ "": "": "" } }'));

Resulting in:

bool(true)
bool(false)

A Step Towards Clarity: Typed Constants and Dynamic Access
The introduction of typed constants in PHP 8.3 is a revolutionary feature that will greatly enhance the clarity and reliability of PHP code. Additionally, the newfound ability to access constants dynamically further contributes to the overall robustness of the language.

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 = [];
}

Randomizer Class Improvements: Enhanced Randomness
Expanding upon the Randomizer class that was introduced in PHP 8.2, PHP 8.3 introduces three additional methods:

getBytesFromString(): Selects a specified number of characters from a string in a random manner.

getFloat(): Generates a random floating-point number within a specified range.

nextFloat(): Similar to getFloat, but always returns a floating-point number between 0 and 1, without the need for any parameters.

$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

The #[\Override] attribute serves as a protective measure, guaranteeing that a method genuinely overrides a method in the parent class.

PHP will now generate an error if the method is not present in the parent class, thereby minimizing the chances of unintended consequences during code development.

class Test {
    #[\Override]
    public function myMethod(): void {}
}
Fatal error: Test::myMethod() has #[\Override] attribute, but no matching parent method exists in ... on line ...

Leave a Reply