PHP8 – The Hell is This? EASY EXPLANATION

PHP8 – The Hell is This? EASY EXPLANATION

It’s early December 2020 and yes we have received a stable new major version of PHP8. Is it good? better than v7? The hell is that JIT and how easy is to swap your v7 application? Well don’t go anywhere and read this article my PHP developer…

Magic Just-In-Time (JIT) performance

Just-In-Time it’s atually easy to explain. So currently the PHP was parsed language, meaning that once any PHP file was called it would parse (by PHP parser) any other linked PHP files or code sections. Even if such file was never used or called. Let’s have a look at this example

function getAnswer($doYouLikeOmelakBlog) {
    if ($doYouLikeOmelakBlog) {
        echo 'great you win!';
    } else {
        require_once('readMoreOnBlog.php');
    }
}

In PHP7 and older verions when you call getAnswer(true) the PHP parser would still parse the contents of the readMoreOnBlog.php file. With JIT on PHP8 the included file would not be parsed any more.

//by running the line:
getAnswer(true);

//PHP7 and less would parse the readMoreOnBlog.php file in FULL
//PHP8 will skip the whole required file!

What does the above mean? Well, if you ever hear a news that MVC is slow in PHP and it should be replaced with middleware, then guess what? The performance difference is now minimalistic! So there is no reason to ignore MVC any more.

Stop ignoring me, bitch. | Cry For Help Ecard

The new JIT integration implementation started in late 2014, however for unknown reasons this particular extension hasn’t been released since then (hence surprise in PHP8). Even though JIT is a major improvement, it might not give a fast push to the web-based websites due to the nature of these projects. The best cases for Just-In-Time compilation are all continuously running process, like Java or Node.js. This can lead to creation of sandbox running PHP similar to Node.js approach, but this has not been mentioned anywhere yet.

Consistent Type Errors

How to stop the small mistakes that are slowly killing your company - The  Business Journals

Even though TypeErrors have been introduced in 7.0, not all the areas have been updated yet. Some of the sections still fail by returning NULLs. The most userland function already throws them, but the internal function still has some edge cases and wrong behaviours.

//PHP7
strlen([]); // Warning: strlen() expects parameter 1 to be string, array given

//PHP8
strlen([]); // TypeError: strlen(): Argument #1 ($str) must be of type string, array given

Optional Arguments in Function Calls

Specify which optional parameters you set by calling their aliases, instead of passing nulls in front:

//signature of mail()
mail ( string $to , string $subject , string $message [, mixed $additional_headers [, string $additional_parameters ]] ) : bool

//PHP 7
mail('adam@omelak.com', 'Test subject', 'Message', null, $extraParams);

//PHP8
mail('adam@omelak.com', 'Test subject', 'Message', additional_parameters: $extraParams);

Shortcut for Constructor Properties

Are you lazy programmer? If so, you can defin your class properties inside of contrcutor! Now that’s awkward…

//PHP8
class MyClass {
  public function __construct(
    public bool $a = true,
    public int $b = 1,
    public string $c = 'a property in constructor, woop!',
  ) {}
}

Multi Types

The Happy Birthday Song: All Together Now! - Nelligan Law

Aka, “Union Types” allows now to define more than one type for property, separated by pipes:

//PHP8
private int|float $number

New “match()” Expression

Scratch Games Double Match - Minnesota Lottery

Another shortcut for common switch() statement, which doesn’t require keywords like break, case or default:

//PHP8
match ('thirdCase') {
  'firstCase' => "Nope!",
  'secondCase' => "Still nope",
  'thirdCase' => 'Hell yeah!'
};
//returns: Hell yeah!

Nullsafe Operator

Security and Policing 2021 - Safer Handling - Security and Policing 2021

Now finally, something which should be available in PHP 7 a while ago, nullsafe operator allows you to call methods, properties on some object which may or may not be empty, null. For instance:

//PHP7
if (isset($user)) {
   if ($user->getProfile() !== null) {
       echo $user->getProfile()->getName();
   }
}

//PHP8
echo $user?->getProfile()?->getName();

Confusing Attributes in Comments

Another way for adding comments. Just use the hash character and viola, you are writing documentation by using a structured metadata with PHP’s syntax:

//PHP8
#[Route("/api/users/{id}", methods: ["GET"])]
public function get($id) { /* ... */ }

Upgrade from PHP7 -> PHP8

PHP 8 Release Available With a Host of New Features And Optimizations

You would assume that a transition between 7.4 to 8.0 is smooth right? Well you can’t be more wrong about it. Here are the backward incompatibilities: https://www.php.net/manual/en/migration80.incompatible.php , deprecated bits: https://www.php.net/manual/en/migration80.deprecated.php and finally some other changes: https://www.php.net/manual/en/migration80.other-changes.php

Please follow and like us:

Leave a Comment