PHP 8: The Five Most long-awaited Updates and What they Mean

Raindrops Infotech
7 min readNov 30, 2021

Raindrops infotech

The Five Most long-awaited Updates and What they Mean

PHP that started as an open source project in 1994, is one of the most popular server-side scripting or programming languages. It is used to deliver dynamic content, maintain database connections, session tracking, email, file uploads, and build feature-rich e-commerce sites.

Website developers in California or India, East Europe or Brazil, all use PHP to build their dynamic websites for schools, hospitals, blogs, stores, any many more such projects because it is easy, simple, powerful and dynamic.

PHP can integrate with any database engine including MySQL, Oracle, MS SQL Server, PostgreSQL, Sybase, and Informix.

Clients routinely hire PHP developers in India to maintain their existing websites, upgrade them, revamp them or to build an entirely new website with great appeal and zippy functionality.

New Features in PHP 8

PHP 8 is releasing on November 26, 2020 and it is a new major edition, bringing with it some path-breaking revisions and additions. The official PHP RFC states more than 35 major and minor changes, updates, new features and performance improvements.

These major improvements that we are going to discuss are phenomenal and there is a greater chance that you may need to make some changes to your code to make it more secure, efficient and robust.

Some of new features of PHP 8 such as the JIT compiler, union types, the mixed type, the match expression, etc. are real improvements over the last major release of PHP, the version 7.4.

1. New Features

(1) Union types
(2) Just-In-Time (JIT) Compiler
(3) The null safe operator
(4) Named arguments
(5) Attributes
(6) Match expression
(7) Constructor property promotion
(8) New static return type
(9) New mixed type
(10) Throw expression
(11) Inheritance with private methods
(12) Weak Maps
(13) Allowing ::class on objects
(14) Non-capturing catches
(15) Trailing comma in parameter lists
(16) Create DateTime objects from the interface
(17) New Stringable interface
(18) Abstract methods in traits improvements
(19) Object implementation of token_get_all()
(20) Variable syntax tweaks
(21) Type annotations for internal functions
(22) ext-JSON always available
(23) Consistent type errors
(24) The @ operator no longer silences fatal errors
(25) Default error reporting level
(26) Concatenation precedence
(27) Stricter type checks for arithmetic and bitwise operators
(28) Namespaced names being a single token
(29) Saner numeric strings
(30) Saner string to number comparisons
(31) Reflection Method Signature Changes
(32) Stable Sorting
(33) Fatal Error for Incompatible Method Signatures

2. Reclassified Engine Warnings

3. New PHP Functions

(1) New str_contains() function
(2) New str_starts_with() and str_ends_with() functions
(3) New fdiv() function
(4) New get_debug_type() function
(5) get_resource_id() function

Here is our list of the seven major new features of PHP 8.

1. Union Types

A Union, as the name suggests, is a grouping of multiple types. Union types, in programming languages, accept values that can be of different data types. As of now, PHP does not have support for union types. with the exception of the ?Type syntax and the special iterable type.

Considering the dynamically typed structure of PHP, there are plenty of situations where union types can be useful.

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

As many functions (like strpos(), strstr(), substr(), etc.) include false among the possible return types, the false pseudo-type is also supported. The void can never be part of a union type. 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;

Before PHP 8, union types could only be specified in phpdoc annotations. Now, support for union types will be added in function signatures and they would define union types with a T1|T2|… syntax instead:

class Number {

private int|float $number;

public function setNumber(int|float $number): void {

$this->number = $number;

}

public function getNumber(): int|float {

return $this->number;

}

}

Supporting union types allows a programmer to move more type information from phpdoc into function signatures. It brings with the following advantages:

  • strict enforcement of types, so mistakes are caught early.
  • Type information is less likely to become outdated or miss border-cases.
  • Types are checked during inheritance, enforcing the Liskov Substitution Principle that any method should return the same type as that of its parent.
  • Type information is accessible at runtime through reflection.
  • The syntax is a lot more formal than phpdoc.

2. The Just-In-Time Compiler (JIT Compiler)

JIT is already a part of the PHP 7.4 in a dormant mode, but in the PHP 8.0 version, its performance and usability is significantly improved.

JIT is a compiling strategy in which a source code is compiled on the fly, at runtime, into a CPU’s native object code that is usually faster than the interpreted code. To achieve this, the JIT compiler needs access to dynamic runtime information. A regular compiler does not have that information, so even the interpreted languages with JIT compiler can run efficiently.

As per the RFC proposal, PHP JIT is implemented as an independent part of OPcache. The programmer has the control to enable or disable it at PHP compile time and at run-time. When JIT is enabled, native code of PHP files is stored in an additional region of the OPcache shared memory and the system variable op_array→opcodes[].handler(s) keep pointers to the entry points of JIT compiled code.

To better understand, let us look at how PHP executes from the source code to the result. The PHP execution is a 4-stage process:

  • Lexing/Tokenizing:

First, the interpreter reads the PHP code and builds a set of tokens.

  • Parsing:

The interpreter checks if the script matches the syntax rules and uses tokens to build an Abstract Syntax Tree (AST), which is a hierarchical representation of the structure of source code.

  • Compilation:

The interpreter traverses the tree and translates AST nodes into low-level Zend opcodes, which are numeric identifiers determining the type of instruction performed by the Zend VM.

  • Interpretation:

Opcodes are interpreted and run on the Zend VM.

As PHP is an interpreted language, it means when a PHP script runs, the interpreter parses, compiles, and executes the code repeatedly on each request. This results in wasting of CPU resources and time.

OPcache improves performance by storing precompiled bytecode in shared memory, eliminating the need for PHP to load and parse scripts on each request. With OPcache enabled, the PHP interpreter goes through the 4-stage process only the first time.

Even if opcodes are in the form of low-level bytecodes, they still must be translated into machine code. JIT uses DynASM (Dynamic Assembler) to generate native code directly from PHP bytecode. Or, in short, it translates the hot parts of the bytecode into machine code completely bypassing compilation and bringing considerable improvements in performance and memory usage.

3. Named arguments

Named arguments to methods allow you to pass in values in any order by using their argument names. This is a major relief, because by specifying the value name the function calls can be more specific, clear and you can easily leave out the optional arguments without any confusion.

Take a look at the example below:

function foo(string $a, string $b, ?string $c = null, ?string $d = null) {

/* function definition */

}

/* function call */

foo( b: ‘value b’, a: ‘value a’, d: ‘value d’, );

4. Match expression

The new match expression can be called the switch expression on steroids!

PHP 8 introduces the new match expression. It is a powerful feature that will prove to be often a better choice to use. There are many differences in the switch and the match expressions:

  • The match expression is significantly shorter to code,
  • It can return values
  • It needs no break statements,
  • The match can combine conditions,
  • It does not coerce any type.

Here’s a switch example:

switch ($statusCode) {

case 200:

case 300:

$message = null;

break;

case 400:

$message = ‘not found’;

break;

case 500:

$message = ‘server error’;

break;

default:

$message = ‘unknown status code’;

break;

}

And here is its match equivalent:

$message = match ($statusCode) {

200, 300 => null,

400 => ‘not found’,

500 => ‘server error’,

default => ‘unknown status code’,

};

5. New mixed type

A missing type can mean a lot of things in PHP code:

  • A function returning nothing or null
  • The return value may be one of many types
  • The return value is a type that cannot be suggested in PHP

Due to the above reasons, it is a good idea to add the mixed type. mixed may represent any type PHP supports, and therefore you cannot cast a variable to mixed because it will not make any sense.

mixed can mean one of the following types: float, null, object, resource, string, array, bool, callable, and int.

it is important to note that, in addition to the return values, mixed can also be used as a parameter or property type. Ans as mixed already includes null, it is not allowed to make it nullable.

The following will trigger an error:

function bar(): ?mixed {}

mixed is equivalent to a union type of:

string|int|float|bool|null|array|object|callable|resource

With mixed available, you can now declare mixed as the type when the parameters, returns, and class properties can be of any type., for example, look at the below code:

class Example {

public mixed $exampleProperty;

public function foo(mixed $foo): mixed {}

}

Conclusion

At Raindrops Infotech, we are committed to deliver the best and the latest in technology to our diverse array of clients. We regularly invest in training and development of our development team in the latest tools, technologies, paradigms and updates.

This way our team can deliver for you the most efficient, secure and robust solutions. Our experienced and professional team of PHP developers is all set to embrace and work with PHP 8 as and when it is released and unleash the full of the improvements for your benefit.

You can hire a PHP Developers now.

Originaly publish At Raindropsinfotech.com Nov 30 2012

--

--

Raindrops Infotech

Raindrops Infotech is a top web development company in the USA, specializing in website design and web development agency. https://www.raindropsinfotech.com/