The new major VERSION of PHP, PHP8, is expected to be released by the end of 2020.

It’s in very active development right now, so the pace and progression of development could change a lot over the next few months.

Official group click here.

In this article, I’ll outline some of the changes that will be coming in PHP8: new features, performance improvements, and breakthrough changes.

Because PHP8 is a new major release, the code and syntax will be less downward compatible.

If you keep up with the latest version, upgrading shouldn’t be too difficult, since most of the breakthrough changes were deprecated in the 7.* release.

In addition to the groundbreaking changes, PHP8 also brings some nice new features, such as the JIT compiler and Union types, and much more.

New features

It starts with new features, but PHP8 is still under active development, so the list will grow over time.

Union types RFC

Given the dynamic typing nature of PHP, combined types can be useful in many situations.

A union type is a collection of two or more types that indicate that either of the two types can be used.

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

I feel like this is similar to the union in C.

Note that void can never be part of a union type because it means “no return value at all.”

In addition, you can use | NULL or use existing? .

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

JIT RFC

The JIT- just-in-time compiler promises significant performance gains, although there may not be significant benefits In Web applications.

There aren’t any precise benchmarks at this point, but they’re definitely coming.

Static Return Type RFC

Although it is already possible to return self, before PHP8, static was not a valid return type. Given the dynamic typing nature of PHP, it is useful to many developers.

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

Weak maps RFC

The WeakMap implementation was added in PHP 8, based on the WeakRefs RFC added in PHP 7.4. WeakMap contains references to objects, which does not prevent them from being garbage collected.

Orms, for example, often implement caches containing references to entity classes to improve the performance of relationships between entities.

These entity objects cannot be garbage collected as long as the cache has references to them, even if the cache is the only thing that references them.

If the cache layer is changed to use weak references and maps, PHP will garbage collect these objects when they are no longer referenced by other objects.

Especially in the case of ORM, it can manage hundreds (if not thousands) of entities in a single request; Weak maps can provide a better, more resource-friendly way to work with these objects.

Here is an example of the use of Weak maps in RFC:

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

You can use ::class RFC on objects

A small but useful new feature: you can now use: : class on objects instead of get_class() on them.

It works in the same way as get_class().

$foo = new Foo();
var_dump($foo::class);Copy the code

Interface to create a DateTime object

You can already create a DateTime object from a DateTimeImmutable mutable object using DateTime: : createFromImmutable($immutableDateTime), but the converse is tricky.

By adding DateTime: : createFromInterface() and DatetimeImmutable: : CreateFromInterface (), now has a general way to convert DateTime and DateTimeImmutable objects to and from each other.

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

New Stringable interface 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 interface behind the scenes and does not need to implement it manually.

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

New str_contains () function 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.

Before:

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

Now:

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

The new fdiv () function PR

The new fdiv () function acts like the fmod () and intdiv () functions, which allow divisible by 0.

Instead of errors, you’ll get INF, -INF, or NaN, depending on case.

New get_debug_type () function RFC

  • Get_debug_type () returns the type of a variable.
  • Sounds like something getType () could do.
  • Get_debug_type () returns more useful output for arrays, strings, anonymous classes, and objects.
  • For example, calling getType () on class \foo\Bar returns Object.
  • Using get_debug_type () returns the class name.
  • A complete list of the differences between get_debug_type () and getType () can be found in the RFC.

Improved the abstract method RFC in Traits

Traits can specify abstract methods that must be implemented by classes that use them.

But there is a caveat: prior to PHP8, the signatures of these method implementations were not verified.

Valid in the following code:

trait Test {
 abstract public function test(int $input): int;
}
class UsesTrait
{
 use Test;
 public function test($input)
 {
 return $input; }}Copy the code

When traits are used and abstract methods are implemented, PHP8 performs the correct method signature validation.

This means you need to rewrite the following:

class UsesTrait
{
 use Test;
 public function test(int $input): int
 {
 return $input; }}Copy the code

Object interface RFC for token_get_all ()

The array_array () function returns an array of values.

This RFC adds a PhpToken class using the PhpToken:: Getall () method.

This implementation uses objects instead of ordinary values.

It consumes less memory and is easier to read.

Variable syntax adjusts RFC

From the RFC: “Uniform variable Syntax RFC resolves some inconsistencies in PHP variable syntax”, this RFC is intended to resolve a few overlooked cases.

Type annotation for internal functions

Many people are involved in adding appropriate type annotations to all the internal functions.

This has been a long-standing problem, and with all the changes made to PHP in previous versions, it will eventually be resolved.

This means that internal functions and methods will have complete type information in reflection.

Unified error type RFC

The user-defined function in PHP already throws TypeErrors, but the internal function does not throw TypeErrors, instead issuing a warning and returning NULL.

Since PHP8, the behavior of internal functions has been consistent.

Zend Engine reclassified RFC error

Many errors that previously only triggered warnings or notifications have been transformed into appropriate errors.

The following warning has been changed.

Undefined variables: Error exceptions instead of notifications.

Undefined array index: warning instead of notification.

Divided by zero: DivisionByZeroError exception rather than warning.

Try incrementing/decrementing the non-object property ‘% s’ : error exception instead of warning.

Attempted to modify non-object property ‘% s’ : error exception instead of warning.

Attempt to assign a non-object attribute ‘% s’ : error exception instead of warning.

Create default objects from null values: error exceptions instead of warnings.

Trying to get non-object property ‘% s’ : warning instead of notification.

Undefined attribute: % s: : $% s: warning rather than notification.

Cannot add element to array because the next element is occupied: error exception instead of warning.

Unable to cancel setting offsets in non-array variables: error exception rather than warning.

Scalar values cannot be used as arrays: error exceptions rather than warnings.

Can only unpack arrays and traverse: TypeError exceptions rather than warnings.

Invalid argument provided for foreach () : TypeError exception instead of warning.

Offset type illegal: TypeError exception instead of warning.

The offset type in ISSET is illegal or empty: TypeError exception rather than warning.

Unset offset type illegal: TypeError exception rather than warning.

Array-to-string conversion: warning instead of notification.

The resource ID#% d is used as an offset, converted to an integer (% d) : warning instead of notification.

String offset conversion occurs: warning instead of notification.

Uninitialized string offset: % d: warning instead of notification.

Unable to assign an empty string to a string offset: error exception rather than warning

Default error reporting level

Now it’s E_ALL, not everything except E_NOTICE and E_DEVERATED.

This means that many bugs may pop up that were quietly ignored before, even though they may have existed prior to PHP8.

The @ operator no longer ignores fatal errors

This change may reveal errors that were hidden prior to PHP8. Be sure to set display_errors=off! On the production server.

Cascaded priority RFC

Although it is no longer recommended in PHP7.4, this change is now effective.

If you write like this:

echo "sum: " . $a + $b;Copy the code

PHP used to interpret it like this:

echo ("sum: " . $a) + $b;Copy the code

PHP 8 will explain it like this:

echo "sum: " . ($a + $b);Copy the code

Reflection method signature changes

Three method signatures for reflection classes have changed:

ReflectionClass::newInstance($args);
ReflectionFunction::invoke($args);
ReflectionMethod::invoke($object.$args);Copy the code

It has become:

ReflectionClass::newInstance(...$args);
ReflectionFunction::invoke(...$args);
ReflectionMethod::invoke($object.$args);Copy the code

The upgrade guide specifies that if you extend these classes and still want to support both PHP 7 and PHP 8, the following signatures are allowed:

ReflectionClass::newInstance($arg = null, ...$args);
ReflectionFunction::invoke($arg = null, ...$args);
ReflectionMethod::invoke($object.$arg = null, ...$args); Copy the code


To learn more, please visit:

Tencent T3-T4 standard boutique PHP architect tutorial directory directory, as long as you finish the guarantee salary rise a step (continue to update)

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.