PHP 8 New Features [September's updates]

Coding (PHP 8)

Sep 10, 2020

What are the new features and changes of on PHP 8? let's discover them!
 
/img/blog/php-8-new-features.jpg

Introduction

 

Less than 12 weeks and we are going to see another milestone achieved by our favourite programming language.

 

The 26th of November, in fact, the new stable version of PHP 8 will be officially released.

 

Since August the 4th, the version is in feature freeze.

 

It means that no more RFC are applied and the features that have accepted are the only one we are actually going to see.

 

Even if this does not sound too good, there is no need to worry, there are going to be plenty of new features and syntax hacks available for us to playing around.

 

My goal with this post, and a few other posts in the coming weeks is to keep you up-to-date with the latest news about PHP 8 so we will be as ready as we can be when the new version will be finally released.

 

If you want to be notified every time a new post is published take advantage of the newsletter by inserting your email.

 

Let's jump into it!

 

A look into PHP 8 the series

 

The goal of this series is to get you ready to work with the latest version of this beautiful backend language.

 

The episode of the series are (in chronological order):

  • September's updates the collection of all the most important features and changes a month before they arrive at our machine 
  • New Features the list with explanation of all the new toys we will have in our arsenal
  • Changes Discover all the new improvements, syntax fixes and new features of PHP 8
  • JIT We have heard about JIT for a long time and it almost among us, learn all there is to know about it

 

Table of Content

 

Timeline
New features
    Syntax
        str_contains

        str_starts_with

        str_ends_with

        fdiv

        get_debug_type

        get_resource_id

        Union types

        Named arguments

        nullsafe operator

        Attributes, commonly known as annotations

        Constructor property promotion

        New mixed type

        Trailing comma in parameter lists 

    Operations

        JIT

        ext-json always available 

        Match expression

    Behaviours

        Throw expression

        New static return type 

        Alternative to get_class()

        Inheritance with private methods

        Weak maps

        Non-capturing catches

        Create DateTime objects from interface

        New Stringable interface

        Abstract methods in traits improvements

        implementation of token_get_all
Changes

    Consistent type errors

    Reclassified engine warnings

    The @ operator no longer silences fatal errors

    Default error reporting level

    Default PDO error mode

    Concatenation precedence

    Stricter type checks for arithmetic and bitwise operators

    Namespaced names being a single token

    Saner numeric strings

    Safer string to number comparisons

    Reflection method signature changes

    Stable sorting

    Fatal error for incompatible method signatures

 

 

A look into PHP 8 the series

 

The goal of this series is to get you ready to work with the latest version of this beautiful backend language.

 

The episode of the series are (in chronological order):

  • September's updates the collection of all the most important features and changes a month before they arrive at our machine 
  • New Features the list with explanation of all the new toys we will have in our arsenal

 

Timeline

 

To start with, let’s talk about what’s on our schedule.

 

As said, from the beginning of August there won’t be any new feature added to the project, 

 

It will follow 3 series of beta.

 

Then it will be the time for several rounds of release candidates, in order from PHP 8.0-RC1 to PHP 8.0-RC5, they will occur during the autumn months of 2020.

 

Below you can see a table with all the dates.

 

To have a deeper understanding of what it is going to happen to check out the Preparation Tasks page of PHP8.

 

 

 

Become a Patron!

 

 

New features

 

It is time for the nitty-gritty of this post. 

 

The reason you are reading this!

 

What are the new features? What will you be able to do with the language from this winter onward?

 

Starting with syntax changes and various improvements we are going to see quite a lot of new tricks and functions available on the PHP core arsenal.

 

 

Syntax

 

str_contains() 

 

How would you check if a string is contained inside another string?

 

The best way to do that so far is by using the strpos() function and indicate the needle you are looking for.

 

The returned value of this function is an integer that indicates the position for the first character on the string we are looking for (the needle).

 

If the needle is not found strpos() returns 0 which count as false in a conditional statement.

 

$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);

if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}

 

This works but clearly in 2020 is not the best way this should be done.

 

What the new solution then?

 

if (str_contains($mystring, $findme)) {
    echo "The string '$findme' was found in the string '$mystring'";
} else {
    echo "The string '$findme' was not found in the string '$mystring'";
}

 

This solution is way neater and easy to read for a beginner developer

 

 

str_starts_with() 

 

Here is another PHP function that, in my opinion, should have been implemented a long time ago but thanks to the new speed of the language it only makes sense now.

 

The question this function answer is:

 

How to check if a string starts with a specified string?

 

The solution up to PHP 7.4 would be something like this:

 

If (substr($mystring, 0, strlen($findme)) === $findme))

 

Or maybe

 

if (strncmp($mystring, $findme, strlen($findme)) === 0)

 

Which to be honest I have never used and I strongly believe you didn’t too.

 

What’s the news then?

 

if (str_starts_with($mystring, $findme)) {
    echo "The string '$mystring' starts with the string ‘$findme’”;
} else {
    echo "The string '$mystring' does not start with the string ‘$findme’”;
}

 

Another amazing syntax improvement just right there

 

str_ends_with()

 

If you have read the previous paragraph this is pretty straightforward

 

if (str_ends_with($mystring, $findme)) {
    echo "The string '$mystring' ends with the string ‘$findme’”;
} else {
    echo "The string '$mystring' does not end with the string ‘$findme’”;
}

 

If you are having difficulties understanding these snippets head over the Basics of PHP

 

fdiv() 

 

The division by 0 has always been seen as a problem for PHP developers

 

I remember seeing an interview with Rasmus Lerdorf in which he explained why the earliest versions of PHP didn’t have any check against this type of error.

 

The reason was that this is an error so easy to fix that having to write an exception just for this case would not be reasonable in term of performance. 

 

Now that things have changed and PHP is way faster the DivisionByZeroError from the standard division operator is reality.

 

We need a way that actually does not trigger this type of diagnostic.

 

fdiv() that implement floating-point division and its siblings fmod() and intdiv() returns INF, -INF or NAN depending on the cases. 

 

 

get_debug_type() 

 

Imagine to have the following code:

 

$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {
    echo gettype($value), "\n";
}

// output
integer
double
NULL
object
string

 

The output consists of only the type of data, which is exactly what we want in this case,

 

What if, instead, we need a bit more information about these variables?

 

The solution would be to use get_debug_type() function. 

 

 

get_resource_id() 

 

A type of variable you can have in your PHP application is resources.

 

It can contain files or something abstract such as a connection to a database.

 

An id is assigned to each of the resources active in the script and until now if you wanted to get it you should have done it by casting the resource to and an integer type.

 

$id = (int) $resource;

 

An easy syntax enhancement that makes your life way better if you do this often is to use the new function as below.

 

$id = get_resource_id($resource);

 

 

Union types

 

PHP was born as a loosely typed programming language,

 

Even though with the years the trend has been to make it stricter and stricter there is still occasion in which there is the need to take into account a bit of flexibility.

 

PHP 8 implements the possibility to indicate two or more types for a single variable.

 

public function getNumber(int|string $input): int|float;

 

There are some exception to this rule as to when you are using a variable that can be null

 

In this case, you can use the ? ( question mark notation)
 

public function getAddress(string|null $address): string

public function getAddress(?string $address): string

Also, note that this new feature does not work if the values are of type void.

 

public function setAddress(Address $address): void

 

 

Named arguments 

 

As you know the arguments of a function are passed by order.

 

The rule is very strict here and generally, there is nothing we can do.

 

PHP 8 has changed it making this part of the code way more flexible.

 

In the next version of the language, the argument can be passed into a function based on their name too.

 

Look at the following example:

 

class User
{
    public function __construct(
        public string $name,
        public string $email,
        public int $age,
    ) {}
}

$data = new class User(
    name: $input['name'],
    age: $input['age'],
    email: $input['email'],
)

;

 

In this case, age PHP will understand that the second attribute is the age and will be considered at third.

 

This feature takes care of all the errors that can happen as well.

 

Just consider the case we misspell the name of the variable or combine named and ordered arguments is a way that is not accepted.

 

PHP will throw an error specifying what happened and how to fix it.

 

This is a quite complex feature that has several exceptions and way to work at its best.

 

If you want to delve into this Brent at stitcher.io wrote a whole article showing us all the secrets of Named arguments

 

 

Operations 

 

JIT

 

This is the feature the majority of PHP developer around the world is waiting for the most,

 

You see PHP is an interpreted language, 

 

The “interpretation” happens line by line.

 

JIT (that stands for Just In Time) act as a compiler.

 

It compiles some parts of the code during runtime and the effect that you will see is like if your code has been cached.

 

Of course, what we expect from this is a very big improvement in performance and a reduction in execution time.

 

This tested has been officially tested by Pedro Escudero and his studies shown an improvement near 50% from the JIT and non-JIT version of PHP 8.

 

 

ext-json always available 

 

If you came across the string ext-json it likely was because your script needs the extension to make json work and your PHP didn’t have it installed.

 

This, even though not a huge issue required you to check what version of PHP you are running then install the extension that makes the code work properly.

 

This is going to change with the implementation of PHP 8.

 

JSON is so popular right now that it made no sense to keep the extension relative to Json not available in PHP automatically.

 

The good news is that now ext-json will always be available.

 

 

 

Behaviours

 

Throw expression

 

At the current time, it is impossible to throw an exception where only expressions are allowed

 

The RFC by Ilija Tovilo is set to be very helpful because it makes it available to use the throw keyword in places like arrow functions, the coalesce operator and the ternary/elvis operator

 

Since in PHP throw is a statement it makes it impossible to throw exceptions in places where only expressions are allowed, like arrow functions, the coalesce operator and the ternary/elvis operator.

 

This RFC proposes converting the throw statement into an expression so that these cases become possible.

 

Here are a few example of this chage:

 

$callable = fn() => throw new Exception();

$value = !empty($array)
    ? reset($array)
    : throw new InvalidArgumentException();

 

 

New static return type 

 

When learning about OOP in PHP you surely encountered the keyword self,

 

When used inside a class it refers to the same class in which the new keyword is actually written.

 

Since the self keyword is used in static classes, which are classes that do not require an instantiated object in order to work,

 

This keyword refers to the class members, and not for particular objects. 

 

Is not rare to see a method that returns new instantiation of their own class.

 

Something like this for example:

 

public static function create(Array $data = []) : self
{
    return new self($data)
}

 

With the implementation of PHP 8 is now possible to return the type of static too.

 

public function create(Array $data = []) : static
{
    return new static($data)
}

 

 

Alternative to get_class()

 

If you wanted to retrieve the class of a selected object until now you had to rely on the PHP function get_class()

 

This function takes an object as a parameter and returns a string with the name of the class the object represent

 

// create an object
$mercedes = new Car();

// external call
echo "class name is " , get_class($mercedes) , "\n";

// class name is Car

 

Even though this is quite straightforward and easy to implement PHP 8 implements an enhancement on the syntax.

 

From release day in fact we can simple do this:

 

// create an object
$mercedes = new Car();

// external call
echo "class name is " , $mercedes::class , "\n";

// class name is Car

 

The result will be the same.

 

 

 

 

Conclusion

 

PHP 8 is going to officially be among us in just a bit, 

 

These above are just a few updates that the new version is going to add to our arsenal of tools.

 

The guys at the core of the language have been working for months to arrive at this point.

 

And I want you to be ready when the calendar mark will hit the 26th of November of this year.

 

Meanwhile, you can brush up all the current state by reading the new features brought by PHP at its 7.4 version.

 

Or, in case you fancy something more advanced you can opt for Conteinerize your PHP project using Docker  

 

 
 
If you like this content and you are hungry for some more join the Facebook's community in which we share info and news just like this one!

Other posts that might interest you

Coding (PHP 8) Sep 28, 2020

PHP 8 New Features [What you need to know]

See details
Coding (PHP 8) Oct 2, 2020

PHP 8 Changes [what is next?]

See details
Coding (PHP 8) Oct 19, 2020

PHP 8 JIT [most expected feature]

See details
Get my free books' review to improve your skill now!
I don't want to improve