Backend Development

PHP 8.3 Features and Improvements

PHP 8.3 Features and Improvements

PHP 8.3 just released and comes with new features, updates and performance improvements. In this post we list the new new features below.

 

 

 

The new features comes with PHP 8.3:

  • Typed Class Constants.
  • A new function in the JSON extension, the json_validate() function.
  • New getBytesFromString() method.
  • New getFloat() and nextFloat() methods.
  • Dynamic fetching of Class Constants and Enum members.
  • Garbage Collection gc_status() function.
  • Aliasing of built-in PHP Classes
  • New #[\Override] attribute

 

Typed Class Constants

PHP 8.3 support declaring a type to a constant, this is some of the major updates to the PHP language. This update enforces compatibility between base and child classes constant types.

class Product
{
    const float PRICE = 12.7;
}
class User
{
    const int ID = 3;
}
trait Post
{
    protected const string TITLE = 'Sample title';
}
interface PaymentMethods
{
    public const string METHOD = 'card';
}

As shown the type declaration follows the const keyword. const type declaration can be applied in classes, interfaces, traits, and enums.

The valuable thing about const type declaration is with class inheritance like so:

class Base 
{
    const int|float AMOUNT = 5;
}

class Child extends Base
{
    const string AMOUNT = "5";    // Illegal
}

This example will trigger a fatal error:

Fatal error: Type of Child::amount must be compatible with Base::amount of type int|float 

Because the const AMOUNT in the base class has a union type int or float, however in the child class when we declare it as string it will throw the above error as you can allowed only with types int or float:  

class Child extends Base
{
    const float AMOUNT = 5.0;   // Correct
}

 

New json_validate() function

In PHP 8.3 there is json_validate() function included in JSON extension that validates if given string a valid JSON string. Prior to PHP 8.3 we have to do custom workarounds by decoding the string and check if contains any errors, but json_validate() is handy for doing such tasks. 

$valid = json_validate('{"user_id":1,"name":"foobar","email":"email@example.com"}');    // true
$valid = json_validate('{"user_id":1,"name":"foobar","email":"email@example.com"');   // false, invalid object

The json_validate() is beneficial when working with Rest API’s, developers typically expects specific JSON structure passed to their endpoints. 

 

New getBytesFromString() method

The Random class introduced in PHP 8.2 with some methods for random number generation. In PHP 8.3  a new getBytesFromString() method introduced to become part of the random extension. This method is available in \Random\Randomizer class. we can retrieve random bytes from a source string using this method.

$randomizer = new \Random\Randomizer();

$word = "secretword";
$length = 32;

$randomBytes = $randomizer->getBytesFromString($word, $length);
echo $randomBytes;

The getBytesFromString() accepts the $string to get bytes from and the $length.

 

New getFloat() and nextFloat() methods

Also in the Random extension there are two other methods for random numbers which are getFloat() and nextFloat() methods. Recently we have methods like getInt() to generate random integer numbers. In PHP 8.3 the \Random\Randomizer::getFloat() method allow us to generate random floating point numbers.

$min = 0.0;
$max = 3.5;

$randomFloat = $randomizer->getFloat($min, $max);
echo $randomFloat;

getFloat() accepts the $min and $max range to retrieve the random value from. You can find more details about getFloat() method at php.net.

The nextFloat() method is the same as getFloat() and request a random floating point number located between 0 to less than 1. This method accepts no argument:

$randomFloat = $randomizer->nextFloat();

 

Fetching of Class Constants and Enum Members

In PHP 8.3 support to retrieve to dynamic Class Constant and Enum members now available. To understand this feature, let’s consider this example:

class Post
{
    const string STATUS = 'publish';
}

Now supposing that the STATUS const stored in a variable that comes from GET request and we want to retrieve the constant value dynamically.

Prior to PHP 8.3 to get the value of dynamic constant, we can use the constant() function along with :: operator like so:

$status = "STATUS";

echo constant("Post::" . $status);    // publish

In PHP 8.3 we can achieve the same result using the dynamic Fetch support of class constants:

echo Post::{$status};    // publish , works in PHP 8.3 and later

The same behavior applies to Enum Members:

enum Gender: string {
    case Male = 'male';
    case Female = 'female';
}

$gender = 'Female';

echo Gender::{$gender}->value;

 

gc_status() function updates

Another info added to the response of garbage collector gc_status() function in PHP 8.3. gc_status() returns insights about the garbage collector, as it returns an associative array of the system resources such as runs, collected, threshold, etc.

An example of gc_status() in PHP 8.3:

$instance = [];

for ($i = 0; $i < 100000; $i++) {
    $instance[] = new stdClass();
}
gc_collect_cycles();

var_dump(gc_status());


The output will be like shown:

array(12) {
  ["running"]=>
  bool(false)
  ["protected"]=>
  bool(false)
  ["full"]=>
  bool(false)
  ["runs"]=>
  int(0)
  ["collected"]=>
  int(0)
  ["threshold"]=>
  int(10001)
  ["buffer_size"]=>
  int(16384)
  ["roots"]=>
  int(0)
  ["application_time"]=>
  float(0.0058797)
  ["collector_time"]=>
  float(9.0E-7)
  ["destructor_time"]=>
  float(0)
  ["free_time"]=>
  float(0)
}

 

Assigning aliases of PHP built-in Classes

With PHP 8.3 we can assign alias to PHP built-in Classes with the class_alias() function. This feature wasn’t available before < PHP 8.3. Once assigned alias you can reference the class using the alias name throughout the entire code.

class_alias(\XMLReader::class, 'MyXmlReader');

$xml = new MyXmlReader();   // Using MyXmlReader alias instead of XMLReader

$xml->open('test.xml');

 

New #[\Override]

PHP 8.3 added a new attribute #[\Override] , this importance of this attribute comes in terms of class inheritance and method overriding . This attribute once added to the method signature, it ensures that a method with the same name already exists in the parent class or in an implemented interface. 

Class BasePrinter
{
    public function print_paper()
    {
        echo "calling print_paper";
    }
}

class Printer extends BasePrinter
{
    #[\Override]
    public function printe_paper()
    {
        
    }
}

This example will trigger a fatal error like this:

PHP Fatal error:  Printer::printe_paper() has #[\Override] attribute, but no matching parent method exists

That’s because i added #[\Override] attribute to the child method, the compiler will look for a method with same name in the parent class but the method has mistypo it should be print_paper() and for this it showing the error. 

 

These are some of PHP 8.3 features. Go to php.net release page for the full details.

 

0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments