PHP 8.3 typed class constants, a json_validate function, override attribute and more

2023/11/24 php Total 3487 Character,about 10 minute

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

Typed Class Constants

What are typed class constants?

Typed class constants are a new feature in PHP 8.3 that allows you to specify the data type of a constant directly within the class definition. This enhances type safety, improves code readability, and facilitates static analysis tools.

Benefits of typed class constants:

  • Improved type safety: Ensures only values of the specified type can be assigned to the constant, preventing errors and unexpected behavior.
  • Enhanced code readability: Explicitly stating the type clarifies the intended use and purpose of the constant.
  • Facilitates static analysis: Allows static analysis tools to identify potential issues and improve code quality.
  • Improved developer experience: Provides a more predictable and consistent way to define class constants.

Example:

class Foo
{
    const string BAR = 'baz';
} 

Previous versions comparison:

Prior to PHP 8.3, defining class constants did not allow specifying the data type directly. Developers had to rely on comments or other methods to document the expected type, but these were not enforced by the language.

Overall, typed class constants offer significant improvements for developers by enhancing type safety, code readability, and static analysis. While not supported in previous versions, upgrading to PHP 8.3 unlocks these benefits and promotes better coding practices.

json_validate() function

Overview

PHP 8.3 introduces a new json_validate() function that is specifically designed for validating JSON strings. This function is much simpler to use than creating your own custom validator, and it is also more efficient than using json_decode() with the JSON_THROW_ON_ERROR flag.

Syntax

The syntax of the json_validate() function is as follows:

json_validate(string $jsonString, string $schemaString)

The jsonString parameter is the JSON string that you want to validate. The schemaString parameter is the JSON schema that you want to use to validate the JSON string.

Return Value

The json_validate() function returns true if the JSON string is valid, and false if it is not valid.

Example

Here is an example of how to use the json_validate() function to validate a JSON string against a JSON schema:

$schema = '{ "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } } }';
$json = '{"name": "John Doe", "age": 30}';

if (json_validate($json, $schema)) {
    echo "Valid JSON";
} else {
    echo "Invalid JSON";
}

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 = 'Symfony';
}
 
$name = 'NAME';
 
// Syntax error in <= v8.2.0
echo Framework::{$name}; // Symfony

New #[\Override] Attribute

class A {
    protected function testA(): void {}
}

// can be found in the parent class // works
class B extends A {
    #[\Override]
    public function testA(): void {}
}

// ovrBest() is not in the parent // FAIL
class C extends A {
    #[\Override]
    public function testC(): void {}
}

Randomizer additions

New Randomizer class. This update brings some small additions:

Randomizer::getBytesFromString(string $string, int $length): string

This method allows you to generate a string with a given length that consists of randomly selected bytes from a given string.

Randomizer::getFloat(
    float $min,
    float $max,
    IntervalBoundary $boundary = IntervalBoundary::ClosedOpen
): float

getFloat() returns a f*loat between $min and $max. You can define whether $min and $max should be included thanks to the IntervalBoundary enum. Closed means the value is included, while Open means excluded.

Randomizer::nextFloat(): float {}

Finally, nextFloat() is a shorthand for getFloat(0, 1, IntervalBoundary::ClosedOpen), in other words: it’ll give you a random float between 0 and 1, where 1 is excluded.

Reference

https://laravel-news.com/php-8-3-0 https://kinsta.com/blog/php-8-3/

Document Information

Search

    Table of Contents

    Lastest Post