PHP 8: News and improvements of the most used backend language – Victor Robles


Recently launched PHP 8, the new version of the popular server-side programming language that we all know.

PHP is one of the most used languages ​​on the web, for many reasons, one of them being its rich ecosystem of technologies around it. Frameworks, libraries, CMS’s, a very broad community, high labor demand have made PHP one of the best backend languages.

PHP 7 brought many performance improvements to the language and is currently the stable version, which you are probably using on your server or on your hosting.

But version 8 of PHP not only brings performance improvements, it also brings new functionalities that will be very useful to those of us who program with PHP.

In the following points we will see what is new in PHP 8.

JIT compiler

One of the main novelties of PHP 8 is the JIT (Just in Time) compiler, which allows you to compile parts of the code on the fly, at runtime.

This functionality has been in preparation for several years and represents an incredible change in the PHP ecosystem, because improves the performance of applications written in PHP 8 and in some cases multiplies it by up to 4.

This will not only improve the performance of applications developed with frameworks such as Laravel or Symfony and with CMS such as WordPress or Drupal, but it also opens the doors to the use of PHP as a programming language for other uses apart from the web.

The JIT compiler can be enabled in the php.ini file, it will allow the native code of the PHP files to be stored in an additional section of the shared OPcache memory in this way:

# Enabling JIT in php.ini
opcache.enable=1
opcache.jit_buffer_size=100M
opcache.jit=tracing

Nullsafe operator

Another novelty is the implementation of the nullsafe operator, which solves a very specific “problem”.
When we want to check in PHP that a property of an object or a method does not return null, we had to be doing ifs to check if that property or method gives us null or not. Now with the nullsafe operator, if the first property, or the first method, returns null, the execution of the entire chain is aborted.

Example in classic PHP:

$universidad =  null;
 
if ($session !== null) {

    $usuario = $session->usuario;
 
    if ($usuario !== null) {
        $estudios = $usuario->getEstudios();
 
        if ($estudios !== null) {
            $universidad = $estudios->universidad;
        }
    }
}

Example in PHP 8:

$universidad = $session?->usuario?->getEstudios()?->universidad;

This saves time and favors cleaner code.

Named parameters

In other programming languages ​​for years there were parameters or named arguments, which allowed us not to have to follow a specific order when passing parameters to a function, we simply passed the name of the parameter and its value and with that it was enough. Well, this has been implemented in PHP 8 and the order of the parameters no longer has to match.

Function example in PHP:

function mostrarCurso($nombre, $profesor, $horas){
   return "Bienvenido al $nombre, impartido por $profesor, que tiene $horas horas de contenido :)";
}

Example invoke function in PHP 8:

echo mostrarCurso(
    horas: 56,
    nombre: 'Master en PHP',
    profesor: 'Víctor Robles'
);

So we can put the order we want in the arguments. It can also be done in a classic way:

echo mostrarCurso('Master en PHP', 'Víctor Robles', 56);

It is a good news.

Match Expression

PHP8 brings a new expression or “control structure” similar to switch, but easier to write and with the ability to return values.

This works the same as a switch:

$genero_id = $_POST["genero_id"];

$genero = match($genero_id ) {
    1 => 'Hombre',
    2 => 'Mujer',
    default => 'Otro'
};

echo $genero;

I like it, it’s useful.

Union Types

Normally in PHP, we could specify union types using PHPdoc annotations, now PHP 8 adds support for union types in function signatures, thus saving us a lot of code.

Example in classic PHP:

class Empleado {  

 /**  
  * @var int 
  */  
  private $edad;  

  /**  
   * @param int|float $sueldo
   * @return int|float  
   */  
  public function getSueldoAnual(int $sueldo): int {  
    $anual = $sueldo * 12;
    return $anual;  
  }
 }

Example in PHP 8:

class Empleado {  

  private int $edad;  

  public function getSueldoAnual(int|float $sueldo): int|float {  
    $anual = $sueldo * 12;
    return $anual;  
  }
 }

In this way we can determine what type of data each property, parameter or return we do has.

Expression throw

Now the throw instead of a statement is considered an expression and can be used in more cases.

throw new Exception('Algo va mal!');

It can be useful in some cases.

Property propagation

When we defined a property in PHP, we had to repeat it up to 3 times to use it as object parameters. Now PHP 8 includes this new feature, which was already in technologies like TypeScript, it allows us to greatly reduce the amount of code we write.

Example in classic PHP:

class Persona
{
    public $nombre;
    public $email;
    public $edad;
 
    public function __construct(
       $nombre,
       $email,
       $edad
    ) {
        $this->nombre = $nombre;
        $this->email = $email;
        $this->edad = $edad;
    }
}

Example in PHP 8:

class Persona
{

    public function __construct(
       $nombre,
       $email,
       $edad
    ) {}

}

In PHP8 we do the 3 steps in one.

:: class on objects

To find the full name of a class or its full namespace we can use :: class, this until now we could only use in classes and not in object instances.

Example in a form class in Symfony:

namespace AppController;

use AppEntityTask;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentFormExtensionCoreTypeDateType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;

class TaskController extends AbstractController
{
    public function new(Request $request): Response
    {
     
        $task = new Task();
        $task->setTask('Write a blog post');
        $task->setDueDate(new DateTime('tomorrow'));

        $form = $this->createFormBuilder($task)
            ->add('task', TextType::class)
            ->add('dueDate', DateType::class)
            ->add('save', SubmitType::class, ['label' => 'Create Task'])
            ->getForm();

        // ...
    }
}

In the add method we need to pass the full namespace as the second parameter and we use :: class on a class that we are already using in the current class, to get the full namespace.

Now in PHP8:

$miObjeto = new stdClass;
var_dump($miObjeto::class);

In PHP 8, $ myObject :: class gives us the same result as get_class ($ myObject). If $ myObject is not an object, it will throw a TypeError exception.

And these would be the most important news of the new version of PHP, there are some more things that have been added, but they are not so relevant and there are no changes that break anything from the previous versions, that is, it is programmed exactly the same, the only thing they have added performance level improvements and new functionalities.

If you want to learn more about PHP, I recommend this course: PHP Course, the most complete in Spanish.
And if you want to host your websites made with PHP, I recommend this web hosting: Good, fast and cheap PHP hosting.


Like it? Share with your friends!

0 Comments

Your email address will not be published. Required fields are marked *