Learn PHP 8 in 5 minutes

Ulugbek Miniyarov
4 min readJan 15, 2021

This is inspired by A half-hour to learn Rust and Learn Go in ~5mins

PHP has come a long way since its version 7 introduction with completely rewritten data structures that drastically improved memory footprint. The recent GA of PHP 8 has made a massive leap with its improved type system and JIT (Just In Time) engine. In this post, I will highlight new features of the language as well as the breaking changes.

Named Arguments

Calling functions or methods with named arguments is now possible:

Attributes

Attributes allow adding metadata information to classes, methods, functions, parameters, properties, and class constants. Reflection API is then used to read the metadata.

#[ is not considered a comment anymore.

Constructor Property Promotion

This is the new handy and concise way of writing classes with properties:

Optional trailing commas

Function or method parameters can now have optional trailing commas.

This is useful for signature updates, especially during reviewing in version control systems.

Union Types

Union types allow types to have multiple type declarations separated by a vertical bar (pipe).

Union Type Gotchas

A pseudo-type false is introduced to avoid backward compatibility break with internal functions such as strpos() that returns false on failures. However, false cannot be used as a standalone type (same goes for null type).

There is also a compile-time guard that checks for redundant and duplicate types.

Mixed Type

Mixed type is equivalent to union type of array|bool|callable|int|float |object|resource|string|null

Match expression

Similar to switch statement, match expression evaluates multiple subject expressions. However, match evaluates in strict check (===) rather than switch weak check (==) where type coercing may happen. Moreover, match is an expression meaning it will return an evaluated expression’s result.

Recap:

  • Match compares in arms in strict mode instead of loosely as done in switch statements
  • Match expressions return value
  • Match expression’s arms don’t fall through to the next cases (meaning does not require an explicit break for each case)
  • Match expression is exhaustive (meaning all potential values of the subject must be evaluated, otherwise throws an UnhandledMatchError exception)

Nullsafe methods and properties

A new nullsafe operator (?->) is introduced for checking nullable values in methods or property calls. This is very similar to calling is_null on each value.

JIT Engine

Although the Just-In-Time Engine was introduced in PHP 8, its implementation was started during PHP 7. Because of its complex nature, it was not added to PHP 7.4 even as experimental. JIT is mostly expected to help long-running CPU-intensive workloads perform better. However, it might not help real-world applications perform any better yet.

https://wiki.php.net/rfc/jit

WeakMap

WeakMaps behave similarly to arrays. However, WeakMaps use objects as keys to values. And these object keys are in weak reference.

Updates to Exceptions

Exceptions are now expressions meaning they can be evaluated in ternary operations. Additionally, catch can ignore assigning a variable to exceptions.

Miscellaneous

ValueError has been added for checking invalid values for arguments. For instance, when a positive value is expected, but a negative is given.

static can be used as a return type (allows late static binding to method returns)

Fetching object class name using variables $object::class instead of get_class($object) is now possible.

Stringable interface is introduced and is automatically added to classes that implement __toString() magic method.

Traits can define abstract private methods to be implemented by classes.

Startup errors on by default (display_startup_errors() ← Careful!)

The @ operator cannot silence fatal errors (Careful!)

Three new string functions added:

// Determine if a string contains a given substring
str_contains ( string $haystack , string $needle ) : bool
// Checks if a string starts with a given substring
str_starts_with ( string $haystack , string $needle ) : bool
// Checks if a string ends with a given substring
str_ends_with ( string $haystack , string $needle ) : bool

To read further on PHP 8 visit official announcement page.

Backward Incompatible Changes

String to Number Comparison: non-strict comparison between numeric and string values now work by casting numeric values to a string. However, numbers compared to numeric strings work as before.

Comparison    | Before | After
------------------------------
0 == "0" | true | true
0 == "0.0" | true | true
0 == "foo" | true | false
0 == "" | true | false
42 == " 42" | true | true
42 == "42foo" | true | false

Method with the same name as the class is not considered as a constructor anymore.

To read further on BC Breaks, visit official page.

Since we are at it why not mention a few gems of PHP 7 too?

Typed class properties

With the release of PHP 7.4, class properties gained type declaration feature.

Arrow functions

Arrow functions are a concise way of writing anonymous functions. They are in form of fn(arguments) => expression

Beware that fn is now a reserved keyword.

Return type covariance and argument type contra-variance

Return type covariance allows a child class to implement its parent’s method with a more specific type.

Argument types in methods can now be less specific in child classes.

FFI (Foreign Function Interface)

Foreign Function Interface extension allows calling C functions from .dll or .so files. Unfortunately, it is still in an experimental state and is not advised to be utilized unless you are familiar with C and its APIs. Moreover, accessing data structures with FFI is slower than accessing native PHP objects. However, FFI data structures may consume less memory. Read about FFI further on the official page.

Preloading

Preloading allows developers to define scripts that will be loaded when the PHP engine starts. Loaded classes, functions, variables, etc., will be available for any script triggered afterwards. However, to clear or change scripts, preloaded scripts PHP engine must be restarted. Major frameworks like Symfony have already implemented preloading to applications.

For further read on PHP 7 visit official migration page.

And with that it should’ve taken 5 minutes (although time is relative, right?)

--

--

Ulugbek Miniyarov

Engineering, Staff @acquia, former Chief Software Architect @enuygun, Creator @lugattj and @zudvpn