New in PHP 8
New in PHP 8
PHP 8, the new major PHP version, is expected to be released by the end of 2020. It's in very active development right now, so things are likely to change a lot in the upcoming months.
In this post I'll keep an up-to-date list of what's expected to come: new features, performance improvements and breaking changes. Because PHP 8 is a new major version, there's a higher chance of your code breaking. If you've kept up to date with the latest releases though, the upgrade shouldn't be too hard, since most breaking changes were deprecated before in the 7.* versions.
Besides breaking changes, PHP 8 also brings some nice new features such as the JIT compiler and union types; and there's more to come!
# New features
Starting with new features, remember that PHP 8 is still in active development, so this list will grow over time.
# Union types RFC
Given the dynamically typed nature of PHP, there are lots of cases where union types can be useful. Union types are a collection of two or more types which indicate that either one of those can be used.
public function foo(Foo|Bar $input): int|float;
Note that void
can never be part of a union type, since it indicates "no return value at all". Furthermore, nullable
unions can be written using |null
, or by using the existing ?
notation:
public function foo(Foo|null $foo): void; public function bar(?Bar $bar): void;
The JIT — just in time — compiler promises significant performance improvements, albeit not always within the context of web requests. There haven't been any accurate benchmarks done at this point, but they sure will come.
If you want to know more about what the JIT can do for PHP, you can read another post I wrote about it here.
# Static return type RFC
While it was already possible to return self
, static
wasn't a valid return type until PHP 8. Given PHP's dynamically typed nature, it's a feature that will be useful to many developers.
class Foo { public function test(): static { return new static(); } }
# Weak maps RFC
Built upon the weakrefs RFC that was added in PHP 7.4, a WeakMap
implementation is added in PHP 8. WeakMaps
hold references to objects, which don't prevent those objects from being garbage collected.
Take the example of ORMs, they often implement caches which hold references to entity classes to improve the performance of relations between entities. These entity objects can not be garbage collected, as long as this cache has a reference to them, even if the cache is the only thing referencing them.
If this caching layer uses weak references and maps instead, PHP will garbage collect these objects when nothing else references them anymore. Especially in the case of ORMs, which can manage several hundreds, if not thousands of entities within a request; weak maps can offer a better, more resource friendly way of dealing with these objects.
Here's what weak maps look like, an example from the RFC:
class Foo { private WeakMap $cache; public function getSomethingWithCaching(object $obj): object { return $this->cache[$obj] ??= $this->computeSomethingExpensive($obj); } }
# ::class
on objects RFC
A small, yet useful, new feature: it's now possible to use ::class
on objects, instead of having to use get_class()
on them. It works the same way as get_class()
.
$foo = new Foo(); var_dump($foo::class);
# Create DateTime objects from interface
You can already create a DateTime
object from a DateTimeImmutable
object using DateTime::createFromImmutable($immutableDateTime)
, but the other way around was tricky. By adding DateTime::createFromInterface()
and DatetimeImmutable::createFromInterface()
there's now a generalised way to convert DateTime
and DateTimeImmutable
objects to each other.
DateTime::createFromInterface(DateTimeInterface $other); DateTimeImmutable::createFromInterface(DateTimeInterface $other);
# fdiv
function PR
The new fdiv
function does something similar as the fmod
and intdiv
functions, which allows for division by 0. Instead of errors you'll get INF
, -INF
or NAN
, depending on the case.
# Type annotations for internal functions EXTERNALS
Lots of people pitched in to add proper type annotations to all internal functions. This was a long standing issue, and finally solvable with all the changes made to PHP in previous versions. This means that internal functions and methods will have complete type information in reflection.
# Variable syntax tweaks RFC
From the RFC: "the Uniform Variable Syntax RFC resolved a number of inconsistencies in PHP's variable syntax. This RFC intends to address a small handful of cases that were overlooked."
# Breaking changes
As mentioned before: this is a major update and thus there will be breaking changes. The best thing to do is take a look at the full list of breaking changes over at the UPGRADING document.
Many of these breaking changes have been deprecated in previous 7.* versions though, so if you've been staying up-to-date over the years, it shouldn't be all that hard to upgrade to PHP 8.
# Consistent type errors RFC
User-defined functions in PHP will already throw TypeErrors
, but internal functions did not, they rather emitted warnings and returned null
. As of PHP 8 the behaviour of internal functions have been made consistent.
# Reclassified engine warnings RFC
Lots of errors that previously only triggered warnings or notices, have been converted to proper errors. The following warnings were changed.
- Undefined variable:
Error
exception instead of notice - Undefined array index: warning instead of notice
- Division by zero:
DivisionByZeroError
exception instead of warning - Attempt to increment/decrement property '%s' of non-object:
Error
exception instead of warning - Attempt to modify property '%s' of non-object:
Error
exception instead of warning - Attempt to assign property '%s' of non-object:
Error
exception instead of warning - Creating default object from empty value:
Error
exception instead of warning - Trying to get property '%s' of non-object: warning instead of notice
- Undefined property: %s::$%s: warning instead of notice
- Cannot add element to the array as the next element is already occupied:
Error
exception instead of warning - Cannot unset offset in a non-array variable:
Error
exception instead of warning - Cannot use a scalar value as an array:
Error
exception instead of warning - Only arrays and
Traversables
can be unpacked:TypeError
exception instead of warning - Invalid argument supplied for foreach():
TypeError
exception instead of warning - Illegal offset type:
TypeError
exception instead of warning - Illegal offset type in isset or empty:
TypeError
exception instead of warning - Illegal offset type in unset:
TypeError
exception instead of warning - Array to string conversion: warning instead of notice
- Resource ID#%d used as offset, casting to integer (%d): warning instead of notice
- String offset cast occurred: warning instead of notice
- Uninitialized string offset: %d: warning instead of notice
- Cannot assign an empty string to a string offset:
Error
exception instead of warning
# Default error reporting level
It's now E_ALL
instead of everything but E_NOTICE
and E_DEPRECATED
. This means that many errors might pop up which were previously silently ignored, though probably already existent before PHP 8.
# The @ operator no longer silences fatal errors
It's possible that this change might reveal errors that again were hidden before PHP 8. Make sure to set display_errors=Off
on your production servers!
# Concatenation precedence RFC
While already deprecated in PHP 7.4, this change is now taken into effect. If you'd write something like this:
echo "sum: " . $a + $b;
PHP would previously interpret it like this:
echo ("sum: " . $a) + $b;
PHP 8 will make it so that it's interpreted like this:
echo "sum: " . ($a + $b);
# Reflection method signature changes
Three method signatures of reflection classes have been changed:
ReflectionClass::newInstance($args); ReflectionFunction::invoke($args); ReflectionMethod::invoke($object, $args);
Have now become:
ReflectionClass::newInstance(...$args); ReflectionFunction::invoke(...$args); ReflectionMethod::invoke($object, ...$args);
The upgrading 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);
# Several small deprecations
During the PHP 7.* development, several deprecations were added that are now finalised in PHP 8.
Would you like to stay up to date about new content? Feel free to subscribe to
my newsletterand follow me
on Twitter. Noticed a tpyo? You can submit a
PRto fix it.
from Hacker News https://ift.tt/30vpWbQ