PHP 8, a big new version of PHP, is expected to be released on December 3, 2020, which means there will be no PHP 7.5 version. PHP8 is currently in a very active development phase, so things could change a lot over the next few months.

In this article, I will maintain an up-to-date list of expected new features, performance improvements, and breakthrough changes. Because PHP 8 is a big new release, your code is more likely to be broken. If you always have the latest version of PHP running, upgrading is relatively easy because most of the major changes are deprecated in the 7. * release.

In addition to major changes, PHP 8 brings some nice new features, such as the JIT compiler, federated types, attributes, and more.

New features

Starting with new features, keep in mind that PHP8 is still in active development, so this list will grow over time.

Joint TYPE RFC

Given the nature of dynamic language typing in PHP, associative types are now useful in many cases. A union type is a collection of two or more types, indicating that any one of them can be used.

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

Note that void is not included in the union type, because void means “no return value at all.” In addition, you can use | null or existing? Expression to represent a union containing nullable:

public function foo(Foo|null $foo): void; public function bar(? Bar $bar): void;Copy the code

JIT rfc

JIT – Just in Time – The compiler, while not always in the context of Web requests, is expected to significantly improve performance. No precise benchmarks have been completed yet, but they will certainly come.

If you want to learn more about WHAT JIT can do for PHP, you can read another article I wrote here.

Attribute the RFC

Attributes, often referred to as annotations in other languages, provide a way to add metadata to a class without having to parse a document block.

For a quick look, here’s an example of a property from the RFC:

use App\Attributes\ExampleAttribute; <<ExampleAttribute>> class Foo { <<ExampleAttribute>> public const FOO = 'foo'; <<ExampleAttribute>> public $x; <<ExampleAttribute>> public function foo(<<ExampleAttribute>> $bar) { } } <<PhpAttribute>> class ExampleAttribute { public $value; public function __construct($value) { $this->value = $value; }}Copy the code

If you want to learn more about how properties work and how to build your own properties, you can read about in-depth properties on this blog.

newstaticReturn type RFC

Although it was already possible to return self, static was a valid return type until PHP 8. Given the dynamic typing nature of PHP, this feature will be very useful to many developers.

class Foo { public function test(): static { return new static(); }}Copy the code

newmixedType the RFC

One might call it a necessary evil: Mixed genres make many people feel confused. However, there is a good argument for implementing it: missing types in PHP can lead to a number of situations:

  • The function returns nothing or a null value

  • We need one type of many types

  • We need a type that can’t be prompted for a type in PHP

For these reasons, adding mixed types is a great thing to do. Mixed itself represents any of the following types:

  • array

  • bool

  • callable

  • int

  • float

  • null

  • object

  • resource

  • string

Note that mixed can be used not only as a return type, but also as a parameter and attribute type.

Also, note that the mixed type cannot be empty because it already includes NULL. The following code triggers a fatal error:

// Fatal error: The mixed type cannot be null, null is already part of the mixed type. function bar(): ? mixed {}Copy the code

Throw expression RFC

The RFC changes the throw from a statement to an expression, which makes it possible to throw exceptions in many new places:

$triggerError = fn () => throw new MyError();

$foo = $bar['offset'] ?? throw new OffsetDoesNotExist('offset');
Copy the code

Weak mapping RFC

The implementation of WeakMaps was added in PHP 8, based on the weak-reference RFC added in PHP 7.4. WeakMaps keep references to objects but do not prevent them from being garbage collected.

Orms, for example, typically implement caching of references to entity classes to improve the performance of associations between entity classes. As long as references to these entity classes exist in the cache, they cannot be collected by the garbage collector, even though they are not referenced anywhere else but in the cache.

If the cache layer uses weak references and weak mappings, PHP will garbage collect those entity classes when they don’t have any other references. With ORMs in particular, it can manage hundreds (if not thousands) of entities in a request; Weak maps can provide a better, more resource-friendly way to handle these objects.

Here is a basic example of weak mapping, taken from RFC:

class Foo 
{
    private WeakMap $cache;

    public function getSomethingWithCaching(object $obj): object
    {
        return $this->cache[$obj]
           ??= $this->computeSomethingExpensive($obj);
    }
}
Copy the code

Allows use on objects::class rfc

A small but useful new feature: instead of using get_class() on objects, you can now use :: class, which works the same way as get_class().

$foo = new Foo();

var_dump($foo::class);
Copy the code

Non-capturing catches rfc

Prior to PHP 8, whenever you wanted to catch an exception, you first had to store it in a variable, whether or not you needed it. You can ignore variables with non-capturing, so replace the following code:

try {
    // Something goes wrong
} catch (MySpecialException $exception) {
    Log::error("Something went wrong");
}
Copy the code

Here’s what you can do now:

try {
    // Something goes wrong
} catch (MySpecialException) {
    Log::error("Something went wrong");
}
Copy the code

Note that the type must always be specified and catch is not allowed to be left blank. If you want to catch all types of exceptions and errors, use Throwable as the catch type.

The trailing comma in the argument list is RFC

Trailing commas are already supported when calling functions, but trailing comma support is still missing in argument lists. This is now allowed in PHP8, which means you can do the following:

Public function(String $parameterA, int $parameterB, Foo $objectfoo,) {//... }Copy the code

Create from interfaceDateTimeobject

You can use DateTime: : createFromImmutable ($immutableDateTime) from DateTimeImmutable object create a DateTime object, and the other is more tricky. By adding a DateTime: : createFromInterface () and DatetimeImmutable: : createFromInterface () now there is a general method, DateTime, and can be DatetimeImmutable objects convert to each other.

DateTime::createFromInterface(DateTimeInterface $other);

DateTimeImmutable::createFromInterface(DateTimeInterface $other);
Copy the code

newStringableInterface RFC

The Stringable interface can be used to type hints for any string or to implement __ toString(). In addition, every time a class implements __ toString(), it automatically implements the background interface instead of manually implementing it.

class Foo { public function __toString(): string { return 'foo'; }} function bar(Stringable $Stringable) {/*... */ } bar(new Foo()); bar('abc');Copy the code

newstr_contains()Function the RFC

Some might say this is long overdue, but we finally don’t have to rely on Strpos to know if one string contains another.

Don’t do this:

if (strpos('string with lots of words', 'words') ! == false) {/*... * /}Copy the code

Here’s what you can do:

If (str_contains('string with lots of words', 'words')) {/*... * /}Copy the code

newstr_starts_with()str_ends_with()Function the RFC

These are two more long-overdue functions that have now been added to the core function.

str_starts_with('haystack', 'hay'); // true
str_ends_with('haystack', 'stack'); // true
Copy the code

Pay attention and don’t get lost

All right, everybody, that’s all for this article. All the people here are talented. As I said before, there are many technical points in PHP, because there are too many, it is really difficult to write, you will not read too much after writing, so I have compiled it into PDF and document, if necessary

Click on the code: PHP+ “platform”

As long as you can guarantee your salary to rise a step (constantly updated)

I hope the above content can help you. Many PHPer will encounter some problems and bottlenecks when they are advanced, and they have no sense of direction when writing too many business codes. I have sorted out some information, including but not limited to: Distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, Laravel, YII2, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell scripting, Docker, microservices, Nginx, etc