Site icon G Tech Group

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

PHP 8.3 code screenshot and new features.

php 8.3 scopriamo tutte le novità

PHP 8.3, rilasciato il 23 novembre, ha introdotto notevoli novità e miglioramenti rispetto alla sua versione precedente, PHP 8.2. Questa versione, pur essendo considerata “minore”, porta con sé cambiamenti significativi che possono impattare notevolmente sullo sviluppo PHP. Scopriamo insieme le principali novità e gli aggiornamenti di 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.

La nuova versione estende la tipizzazione alle costanti di classe, includendo anche quelle in interfacce, trait ed enum. Questa modifica ha l’importante vantaggio di minimizzare il rischio che gli sviluppatori si discostino dall’intento originale di una costante, garantendo maggiore chiarezza e sicurezza nel codice.

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
}

L’efficacia delle costanti di classe tipizzate diventa evidente quando si lavora con classi derivate. Nelle versioni precedenti, una sotto-classe poteva cambiare il valore di una costante, ma con PHP 8.3, ora è possibile prevenire cambiamenti accidentali del tipo di una costante, preservando la coerenza con la dichiarazione originale.

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;
}

Da notare che è possibile “restringere” il tipo di una costante di classe in una sottoclasse, utilizzando un tipo compatibile o più specifico:

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 sintesi, la tipizzazione delle costanti di classe in PHP 8.3 rappresenta un salto di qualità nello sviluppo software. Fornisce ai programmatori uno strumento aggiuntivo per garantire che il codice sia non solo funzionale, ma anche preciso e fedele alle intenzioni originali, riducendo errori e migliorando la leggibilità e la manutenibilità del codice. Questa novità segna un’ulteriore evoluzione della tipizzazione in PHP, consolidando la sua posizione come linguaggio di programmazione moderno e robusto.

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() per controllare gli errori durante la conversione dei dati JSON in array associativi o oggetti. Tuttavia, questo metodo richiedeva l’uso di risorse significative per costruire le strutture di array o oggetti, anche quando il solo scopo era la verifica dell’integrità del 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.

Con l’arrivo di PHP 8.3, è possibile eseguire la stessa operazione in modo più efficiente utilizzando 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(), in quanto ciò impiegherebbe comunque le risorse di memoria per la decodifica. L’approccio ideale è utilizzare json_validate() per confermare la validità del JSON prima di procedere con ulteriori operazioni, come il salvataggio del dato o la sua trasmissione come risposta a una richiesta. In questo modo, si ottimizza l’uso delle risorse e si garantisce un trattamento più efficiente dei dati JSON.

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).

Il problema affrontato era la rigidità nell’utilizzo di classi con proprietà readonly, che limitava alcune possibilità di programmazione. La RFC ha proposto due soluzioni principali:

  1. Permettere l’estensione di classi non-readonly da classi readonly.
  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. Questa nuova funzionalità permette che, durante il deep cloning, le istanze di una classe con proprietà readonly possano essere reinizializzate all’interno del 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;

Questa novità aumenta significativamente la flessibilità nell’utilizzo di classi con proprietà readonly, permettendo di utilizzare pattern di progettazione più avanzati e sofisticati, pur mantenendo l’integrità e la sicurezza che le proprietà readonly offrono.

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

PHP 8.3 ha introdotto un’importante novità che migliora significativamente la chiarezza e la precisione del codice: l’attributo #[\Override]. Questo nuovo attributo è fondamentale quando si lavora con l’ereditarietà e le interfacce in PHP, in quanto fornisce una conferma esplicita che un metodo in una classe figlia è destinato a sovrascrivere un metodo nella classe genitore o a implementare un metodo definito in un’interfaccia.

Problem Solved by #[\Override]: Nella programmazione, può capitare che un metodo in una classe derivata sia scritto con l’intento di sovrascrivere un metodo della classe genitore o di implementare un metodo di un’interfaccia. Tuttavia, errori come refusi nel nome del metodo possono far sì che il metodo non sovrascriva effettivamente quello previsto, portando a comportamenti imprevisti e difficili da individuare.

How #[\Override] works: L’attributo #[\Override] serve a garantire che il metodo in una classe derivata sia effettivamente una sovrascrittura di un metodo della classe genitore o un’implementazione di un metodo di un’interfaccia. Se un metodo contrassegnato con #[\Override] non corrisponde a un metodo nella classe genitore o nell’interfaccia, PHP genererà un errore, rendendo immediatamente evidente il problema.

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

Queste innovazioni in PHP 8.3, sia l’attributo #[\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(). Questo metodo, aggiunto all’estensione Random di PHP, semplifica notevolmente la creazione di stringhe randomizzate da un set di caratteri predefiniti.

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'.

Ponderazione dei Caratteri nell’Input: Un’altra caratteristica distintiva di questo metodo è la possibilità di “pesare” i caratteri nell’input. Se alcuni caratteri compaiono più frequentemente nella stringa di input, avranno maggiori probabilità di essere selezionati nella stringa casuale. Per esempio:

$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 offre una soluzione semplice ed efficace per la generazione di stringhe casuali, con la flessibilità di personalizzare la distribuzione dei caratteri e la lunghezza della stringa risultante. Questo lo rende uno strumento prezioso per una varietà di applicazioni, dall’elaborazione di dati alla sicurezza informatica.

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() sono state introdotte per migliorare l’interazione con il sistema operativo.
  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

Ogni nuova versione di PHP porta con sé anche un elenco di funzioni e impostazioni che vengono deprecate. Queste deprecazioni sono importanti da notare, in quanto l’uso continuato di tali funzioni può portare a warning nei log e potenziali problemi di compatibilità.

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 conclusione, PHP 8.3 rappresenta un significativo passo avanti nello sviluppo del linguaggio, introducendo una serie di nuove funzionalità, miglioramenti e deprecazioni che sono cruciali per modernizzare e ottimizzare il codice PHP. Con l’aggiunta di metodi più avanzati, una maggiore flessibilità e l’introduzione di nuove funzioni, PHP 8.3 si posiziona come una scelta eccellente per gli sviluppatori che cercano di migliorare le prestazioni e la sicurezza delle loro applicazioni.

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.

Questa implementazione è parte dell’impegno di G Tech Group nel fornire le tecnologie più avanzate e aggiornate ai suoi clienti, assicurando che i vostri progetti siano sempre supportati dalle migliori e più recenti soluzioni disponibili sul mercato. Con PHP 8.3 su G Tech Group, potete aspettarvi un ambiente di hosting robusto, sicuro e performante, ideale per sviluppare e far crescere le vostre applicazioni web.

Exit mobile version