What’s new in PHP8 (July 2020 update)

Subscribe to my newsletter and never miss my upcoming articles

Hello neophiliacs! 👋

If you’re like me, a notion PHP8 would wake you up in the middle of the night and you would want to know immediately everything about it.

The release date has been announced to be around the end of November 2020, but some of the new features are already known to be implemented, and some of them are just proposals in a form of RFC and they will probably change or will not be implemented at all.

Table of contents:

  • New features (confirmed)
  • New features (RFC)
  • Breaking changes

I am going to split the news into a comprehensible blocks, so you can follow them as you like.

We will start with…

1. New features (confirmed)

Currently, PHP8 is still under a heavy development so there aren’t really a lot of confirmed features, however proposed features that are in RFC stages do have a high probability to be actually implemented.

1.1 Update for error_reporting()

Starting php8, you will probably get more php errors than ever before. But don’t worry, it’s not because of lots of breaking changes or deprecations, but the default value of reporting errors changes.

PHP used to report “all except for notices, stricts and deprecateds”

E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED

…from this new version, everything will be E_ALL as a default.

1.2 Update for @operator

It will no longer silence fatal errors. If you want to make sure a particular operation runs after the fatal error has been thrown (e.g. memory limit exceeded), you can implement for example register_shutdown_function (for instance for cleanup purposes).

1.3 DateTime::createFromInterface

If you’re using \DateTime while developing, you may have noticed it was easy to create a \DateTime object out of a \DateTimeImmutable class.

However, it was a bit tricky (or almost impossible) to do it other way around.

That’s why there will be a new method that will allow you to do just that:

DateTime::createFromInterface(DateTimeInterface $dateTime);
DateTimeImmutable::createFromInterface(DateTimeInterface $dateTime);

1.4 Reflection class’s methods

This change is a small one, but will have probably big impact (on php frameworks and also lots of stack overflow answers 😂 )

This:

ReflectionClass::newInstance($args);
ReflectionFunction::invoke($args);
ReflectionMethod::invoke($object, $args);

…is now become this:

ReflectionClass::newInstance(…$args);
ReflectionFunction::invoke(…$args);
ReflectionMethod::invoke($object, …$args);

PHP8 upgrade guide specifies, that if you still want to support php7, you will have to do this:

ReflectionClass::newInstance($arg = null, …$args);
ReflectionFunction::invoke($arg = null, …$args);
ReflectionMethod::invoke($object, $arg = null, …$args);

2. New features (RFC)

Now with proposed features, it is a different story now 😉 . There’s quite a few of them so make sure you scroll through and find the one that appeals to you the most! 😎

2.1 Union types

This feature is something I am on seconds thoughts whether I like it or not 🤔. It’s like, when PHP7 emerged, you were able to specify exactly what type of a parameter you are getting to the or from functions – with PHP8 you will be not sure as well.

The proposed syntax is this one:

public function foo(Foo|Bar $input): int|float;

You will be basically able to set a variable into multiple types, so it will not be uncommon to see something like:

public function foo(String|Array|Boolean $input): Array|Float;

Actually, I am looking forward to write such code… can’t wait to see reactions of my colleagues 😂 .

Anyways, this looks totally interesting for me – I can imagine using this when a function returns a “string” and a “boolen” – a string will be a “success message” and “boolean” will be a falsy value.

2.2 JIT compiler

JIT compiler or Just In Time compiler is something announced with php74, but postponed until the latest major version update.

What is does is basically making our favourite php engine way faster than ever before. You can read more information about it here.

2.3 Attributes

If you used to write docblocks for annotations properties for your classes, php8 came up with a way how to make it native in the language. It will be called Attributes. As strange as it may look, it was said to have good to look as it does and the whole discussing was taking place here.

If you were used to this:

/**
 * @property int $id
 */
class User {

    /**
     * @var int
     */
    public $foo;
}

…will become:

@@ExampleAttribute
class User {

    @@ExampleAttribute
    public $foo;
}

I know, I know 😂 but we will get used to it. If you want to learn more about the attributes, there is a great article on this link.

2.4 match expression

Oh man, you’re gonna love this one!

It’s like switch() {} statements on steroids!

$message = match ($httpError) {
    200, 201 => "success",
    404,410 => "not found",
    500, 503 => 'server error',
    default => 'unknown status code',
};

2.5 Constructor property promotion

The name of this one certainly seems interesting! If you hate doing this every time you need to create a new object, php8 creates a shortcut and in order to accomplish this:

class Company {

    public $name;

    public function __construct(string $name) {
        $this->name = $name;
    }
}

…you will just do this:

class Company {
    public function __construct(public string $name) {} 
}

The constructor is useless in this case, but still, this is just a RFC, so maybe the php team will take care of this one as well. 😤

2.6 static return type

Up until this point it was possible to return self. But starting with php8 it will be possible to return static as well.

public function getItem(): static {
    return new static();
}

2.7 mixed as return & argument type

Yes, I know, I know. This is something what we’ve been waiting for alongside with union types.

So to the list of:

  • string
  • integer
  • float
  • bool
  • array
  • object
  • resource
  • null
  • callable
  • mixed

The mixed type already includes null, so this one is necessary and will actually throw and error.

public function commit(): ?mixed {}

2.8 “throw Exception()” becomes an expression

Yeah, instead the “throw” being a statement it becomes an expression and it makes it usable on places never imagined:

$user = User::find($id) ?? throw new NotFoundException();

2.9 calling ::class on objects

This is just a small feature, but if you were used to do this

$className = get_class($object);
$className = MyClass::class;

…you will be able to call ::class on an object as well (which makes get_class in this case useless) and the new syntax will look like this:

$className = $object::class;

2.10 try/catch without a “catch variable”

It happens more often than not, that you just need to catch an exception, but you just don’t need that with the variable catch(Exception $e) {}, you just need catch(Exception) {}.

Soo, this will be possible with php8 😊 .

2.11 trailing comma in parameter list

Do you sometimes write functions parameters into a separate line, to keep the code clean? And have you used to keep a comma after the last parameter only to find out, your IDE is complaining that is not right?

Well, this will not be a problem at all as of php8! It will be allowed to keep a comma after the last parameter of a function or a method.

$result = doAction(
    $items["user"],
    TYPE_USER,
    getMinifiedData(),
);

Can you see the trailing comma? That will be a valid syntax 😎 .

2.12 Stringable interface

Are you using objects in php, that you convert to string on a regular basis? You will welcome this update.

The Stringable interface will be used to type hint anything, that implements __toString() method.

class Foo {
    public function __toString(): string { 
        return 'foo'; 
    } 
} 

function bar(Stringable $stringable) { /* … */ } 

bar(new Foo()); 
bar('abc');

2.13 New functions for working with strings

2.13.1 str_contains()

Indeed! It will be possible to just call str_contains() to check, if a string contains another string. In other words, there will be no need for doing this:

if(strpos($haystack, $needle) !== false) {/**...**/}

2.13.2 str_starts_with()

This new function will allow us to check if a string starts with another string, for example:

str_starts_with('microsoft', 'micro'); // true
str_starts_with('microsoft', 'macro'); // false

2.13.3 str_ends_with()

The same as with the function above, it will be possible to check, whether a string ends with a particular string, for example:

str_starts_with('microsoft', 'soft'); // true
str_starts_with('microsoft', 'hard'); // false

I couldn’t but notice, that php team might have got inspired by ES6, don’t you think? 😉

The same methods "".startsWith(), "".endsWith() and "".includes() were added to JavaScript as well.

2.14 JSON support by default

In the recent years, JSON data type was used day-in-day-out so php team decided to have ext-json enabled and shipped with php by default – similar to date extension.

3. Backwards incompatible changes

Is should be no surprise, that with a major version, there is a bunch of backwards incompatible changes you should be aware when upgrading.

I will list the ones I think will be the most important (but be sure to check each and every one in the official list).

PHP8 incompatibile changes So, let’ have a look at the most prominent ones:

  • an ability to call non-static methods statically was removed
  • __autoload will no longer be available, always use spl_autoload_register instead
  • create_function is no longer available, anonymous functions are suggested to be used instead
  • quite a few warning have been converted to errors (full list here)
  • a bunch of notices have been converted to warnings (attempting to read an undefined variable, attempting to read an undefined property…) (full list here)
  • disabled functions will behave like non-existent ones
  • array access via curly brackets (some people were actually doing that 😀 )

Final notes

What do you say? Do you like any of those? Me personally can not wait to upgrade, because it seems to be there lots of small changes, that are not only useful, but very beneficial.

Even though almost everything is still just RFC right now – we can at least see, how php team is thinking long term and we can see PHP is slowly getting to the next level.

If you liked the information and would like to know more, certainly check out PHP8’s README on this github link:

It provides really comprehensive guide with thorough details of what’s coming.

Except from that, if you’re interested in reading more of my articles about PHP, you can find them in the archive page.

And also if you liked this article, don’t forget to share it with people you like (or maybe also people you don’t like, maybe you’ll became friends! 😆 ).

I will be doing more articles like this in the future and if you want to get notified about them and everything else I release, subscribe to my newsletter right here.

Anyways, thanks for reading and I’ll see you in the next article! 🤓

Yours in coding,

Ivan

Asad Awadia's photo

I really hope people are not starting new projects in 2020 in PHP

Ivan's photo

Hey Asad, PHP team seems to be doing a good job with those updates I think, we will see, where they will go the next time 🤘

Aleem Isiaka's photo

This is a great list here.

Many awesome features are coming into PHP frameworks, and very ambitious StackOverflow answers, LOL!

Ivan's photo

Hello Aleem! Yes, those updates are very interesting! I can't wait till the release of a solid version of PHP8!