PHP 8.3: What's New and Changes in the Latest Version

PHP 8.3 code screenshot and new features.

Table of Contents

PHP 8.3, released on 23 November, introduced significant new features and improvements compared to its previous version, PHP 8.2. This version, although considered 'minor', brings with it significant changes that can have a major impact on PHP development. Let's take a look at the main new features and updates in PHP 8.3.

New Features and Enhancements in PHP 8.3 PHP 8.3 introduced several new features and improvements:

Typed Class Constants in PHP 8.3: A Programming Revolution

PHP 8.3 introduces a revolutionary feature: the typing of class constants. Although PHP had already introduced typing for class properties in PHP 7.4, this innovation had not yet been extended to constants. Until now.

The new version extends typing to class constants, including those in interfaces, traits and enums. This change has the important advantage of minimising the risk of developers deviating from the original intent of a constant, ensuring greater clarity and security in the code.

To illustrate, here is a practical example:

// Correct:
interface ConstTest {
const string VERSION = "PHP 8.3"; // Type and value are both strings
}

// Incorrect:
interface ConstTest {
const float VERSION = "PHP 8.3"; // Type and value mismatch
}

The effectiveness of typed class constants becomes apparent when working with derived classes. In previous versions, a sub-class could change the value of a constant, but with PHP 8.3, it is now possible to prevent accidental changes to the type of a constant while preserving consistency with the original declaration.

For example:

class ConstTest {
const string VERSION = 'PHP 8.2';
}

class MyConstTest extends ConstTest {
// Correct: changing the value of VERSION is permitted
const string VERSION = 'PHP 8.3';

// Wrong: the type must be declared as in the base class
const VERSION = 'PHP 8.3';

// Wrong: it is not possible to change the type declared in the base class
const float VERSION = 8.3;
}

Note that it is possible to 'restrict' the type of a class constant into a subclass, using a compatible or more specific type:

class ConstTest {
const string|float VERSION = 'PHP 8.2';
}

class MyConstTest extends ConstTest {
// Correct: it is possible to specify the type as string or float
const string VERSION = 'PHP 8.3';
const float VERSION = 8.3;

// Correct: although the value could be an int, it is compatible with float
const float VERSION = 8;

// Wrong: it is not possible to extend type options by including int
const string|float|int VERSION = 8;
}

However, it is important to note that two types, void e neverwidely used for the properties and

return values, are currently not supported as types for class constants in PHP 8.3.

In summary, class constant typing in PHP 8.3 represents a quantum leap in software development. It provides programmers with an additional tool to ensure that code is not only functional, but also accurate and true to original intentions, reducing errors and improving code readability and maintainability. This innovation marks a further evolution of typing in PHP, consolidating its position as a modern and robust programming language.

New Function in PHP 8.3: json_validate()

The manipulation of data encoded in JSON is a common practice in the web development. In PHP 8.3, a new function , json_validate()was introduced to significantly improve this process. This function is particularly useful for checking the syntactic validity of a JSON payload before proceeding with its use.

In previous versions of PHP, developers relied on the function json_decode() to check for errors when converting JSON data into associative arrays or objects. However, this method required the use of significant resources to construct the array or object structures, even when the sole purpose was to check the integrity of the JSON.

Here is an example of how the json_decode() to validate a JSON payload:

$obj = json_decode($maybeJSON);

if (json_last_error() === JSON_ERROR_NONE) {
// Executing Operations with $obj
}

In this scenario, resources were mainly used to establish the validity of the JSON payload, which was not very efficient in terms of memory usage.

With the arrival of PHP 8.3, it is possible to perform the same operation more efficiently using json_validate():

if (json_validate($maybeJSON)) {
// Execution of operations with $maybeJSON
}

Important: It should be remembered that it is not optimal to use json_validate() and then pass the data through json_decode()as this would still use up memory resources for decoding. The ideal approach is to use json_validate() to confirm the validity of the JSON before proceeding with further operations, such as saving the data or transmitting it as a response to a request. This optimises the use of resources and ensures more efficient processing of JSON data.

Deep Cloning of Readonly Properties in PHP 8.3

PHP 8.3 introduced a significant improvement in the management of readonly properties in classes. This functionality, initially introduced in PHP 8.1 for individual properties and then extended to entire classes in PHP 8.2, received further development thanks to a recent RFC (Request For Comments).

The problem addressed was the inflexibility of using classes with readonly properties, which limited certain programming possibilities. The RFC proposed two main solutions:

  1. Allow the extension of non-readonly classes from readonly classes.
  2. Allow reinitialisation of readonly properties during cloning.

The second proposal, adopted in PHP 8.3, made a breakthrough in the management of readonly properties. This new functionality allows that, during deep cloning, instances of a class with readonly properties can be reinitialised within the magic method __clone. This means that the functions invoked by __clone can legally modify these properties.

Here is a practical example from the RFC illustrating the new behaviour:

class Foo {
public function __construct(
public readonly DateTime $bar,
public readonly DateTime $baz
) {}

public function __clone() {
// During cloning, $bar will receive a new DateTime object
$this->bar = clone $this->bar;

// This function will be called
$this->cloneBaz();
}

private function cloneBaz() {
// This operation is lawful when called within __clone
unset($this->baz);
}
}

$foo = new Foo(new DateTime(), new DateTime());
$foo2 = clone $foo;

This new feature significantly increases the flexibility of using classes with readonly properties, allowing more advanced and sophisticated design patterns to be used, while maintaining the integrity and security that readonly properties offer.

Introduction to the New Attribute #[\Override] in PHP 8.3

PHP 8.3 introduced an important new feature that significantly improves code clarity and precision: the #[\Override]. This new attribute is crucial when working with inheritance and interfaces in PHP, as it provides explicit confirmation that a method in a daughter class is intended to override a method in the parent class or to implement a method defined in an interface.

Problem Solved by #[\Override]: In programming, it may happen that a method in a derived class is written with the intention of overriding a method of the parent class or implementing a method of an interface. However, errors such as typos in the method name may cause the method not to actually override the intended method, leading to unexpected behaviour that is difficult to detect.

How #[\Override] works: The #[\Override] attribute is used to ensure that the method in a derived class is actually an override of a method in the parent class or an implementation of a method in an interface. If a method marked with #[\Override] does not match a method in the parent class or interface, PHP will generate an error, making the problem immediately apparent.

Practical Example:

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

class B extends A {
#[\Override]
public function ovrTest(): void {} // Correct: overwrites A's ovrTest()
}

class C extends A {
#[\Override]
public function ovrBest(): void {} // Error: ovrBest() does not exist in A
}

Dynamic Retrieval of Class Constants and Enum Members

PHP 8.3 has also simplified the dynamic retrieval of class constants and enum members. Previously, to obtain the value of a class constant or enum member using a variable for the name, one had to use the function constant(). This method was less direct and could be more complex in some scenarios.

Now, with PHP 8.3, it is possible to directly access these constants and members using a simpler, more direct syntax:

class MyClass {
public const THE_CONST = 9;
}

enum MyEnum: int {
case FirstMember = 9;
case SecondMember = 9;
}

$constantName = 'THE_CONST';
$memberName = 'FirstMember';

echo MyClass::{$constantName}; // Direct access to the class constant
echo MyEnum::{$memberName}->value; // Direct access to the enum member

These innovations in PHP 8.3, both the #[\Override] both the improvement in the dynamic retrieval of constants, are important steps towards a clearer, safer and more maintainable code.

PHP 8.3 introduced an innovative and useful method for generating random strings: getBytesFromString(). This method, added to PHP's Random extension, greatly simplifies the creation of randomised strings from a predefined character set.

How getBytesFromString() works: The functionality is rather straightforward. You provide a character string to draw from and specify the desired length for the random string. The method getBytesFromString() will then randomly select bytes from your source string, until the specified length is reached.

Practical Examples:

$rando = new Random\Randomizer();
$alpha = 'ABCDEFGHJKMNPQRSTVWXYZ';

// Generate a random string of 6 characters from $alpha
echo $rando->getBytesFromString($alpha, 6); // E.g.: 'MBXGWL'

An interesting aspect of getBytesFromString() is that it allows random strings longer than the input string to be generated. For example:

$rando = new Random\Randomizer();
$nums = '123456';

// Generate a random string of 10 digits from $nums
echo $rando->getBytesFromString($nums, 10); // E.g.: '2526341615'.

Character Weighting in Input: Another distinctive feature of this method is the possibility of 'weighing' the characters in the input. If certain characters appear more frequently in the input string, they are more likely to be selected in the random string. For example:

$rando = new Random\Randomizer();
$weighted = 'YYYY12345';

// Generate a random string where 'A' is more likely to appear
echo $rando->getBytesFromString($weighted, 5); // E.g.: '1AA53'

In conclusion, the getBytesFromString() in PHP 8.3 offers a simple and effective solution for generating random strings, with the flexibility to customise the character distribution and length of the resulting string. This makes it a valuable tool for a variety of applications, from data processing to computer security.

Other Changes and Improvements in PHP 8.3

In addition to the important new features already discussed, PHP 8.3 introduces a number of improvements and additional functionalities that further enrich the language. Below, we highlight some of these minor updates, which, despite their small scale, can have a significant impact on everyday development.

  1. New Methods for the DOMElement Class: PHP 8.3 enhances DOM handling with additional methods such as DOMElement::getAttributeNames(), DOMElement::insertAdjacentElement(), DOMElement::insertAdjacentText()and others, improving the manipulation of DOM nodes.
  2. Updates for IntlCalendar: The class IntlCalendar has been extended with methods such as IntlCalendar::setDate() e IntlCalendar::setDateTime()offering more flexibility in the management of dates.
  3. Updated LDAP functions: The new functions ldap_connect_wallet() e ldap_exop_sync() extend LDAP integration capabilities.
  4. Improvements in Multibyte Functions: The new function mb_str_pad() adds further options for the manipulation of multi-byte strings.
  5. New POSIX Functions: Functions such as posix_sysconf() e posix_eaccess() have been introduced to improve interaction with the operating system.
  6. New Method in ReflectionMethod: The method ReflectionMethod::createFromMethodName() offers more flexibility in the reflection of methods.
  7. Updated Socket Functions: The function socket_atmark() expands networking capabilities.
  8. New Functions for Strings: str_increment(), str_decrement(), e estream_context_set_options() are some of the new functions introduced for string manipulation.
  9. New Method in ZipArchive: ZipArchive::getArchiveFlag() adds new possibilities for managing ZIP archives.
  10. New INI Setting: La zend.max_allowed_stack_size allows the maximum stack size to be configured, improving resource management.

Deprecations in PHP 8.3

Each new version of PHP also brings with it a list of functions and settings that are deprecated. These deprecations are important to note, as the continued use of such functions may lead to warnings in the logs and potential compatibility problems.

Among the deprecations in PHP 8.3 are:

  • The correction of the constant U_MULTIPLE_DECIMAL_SEPERATORS at U_MULTIPLE_DECIMAL_SEPARATORS.
  • The deprecation of the variant 3MT_RAND_PHP Mt19937.
  • Changes in the ReflectionClass::getStaticProperties().
  • Various INI settings such as assert.active, assert.bailetc., have been deprecated.
  • Calls without arguments to get_class() e get_parent_class() are now deprecated.

PHP 8.3 Available from G Tech Group

In conclusion, PHP 8.3 represents a significant step forward in the development of the language, introducing a number of new features, improvements and deprecations that are crucial to modernising and optimising PHP code. With the addition of more advanced methods, greater flexibility and the introduction of new functions, PHP 8.3 is positioned as an excellent choice for developers seeking to improve the performance and security of their applications.

For those who use hosting and server services, we have good news: G Tech Group has already implemented PHP 8.3 on all its hosting systems and servers. This means that, as a G Tech Group customer, you can immediately enjoy all the benefits offered by the latest PHP version, without the need for manual updates or complex configurations.

This implementation is part of the G Tech Group's commitment to providing the most advanced and up-to-date technologies to its customers, ensuring that your projects are always supported by the best and latest solutions available on the market. With PHP 8.3 on G Tech Group, you can expect a robust, secure and high-performance hosting environment, ideal for developing and growing your web applications.

Leave a comment

Leave a Reply

G Tech Group was born conceptually in 2011 and entrepreneurially in 2013 from an idea of Gianluca Gentile its founder.

The aim was to create the first Social Web Agency not a classic web agency that deals with social but an agency that shares its resources and ideas with other agencies and also connects different agencies, creating a real network.

Recent Posts

Need to raise your site's score?

We have an ideal solution for your business marketing
PHP 8.3, new PHP features, PHP enhancements, PHP deprecations, PHP development
G Tech Group