Menu Close

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

php-8
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
php-8

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:

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.
php-innerblog
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:
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:
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:
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.

Write in to us!

We are just a click away. Let’s hear from you!

    Author Details

    Bharat Koriya

    CEO and Founder of the firm

    Mr. Bharat Koriya is the founder and CEO of Raindrops Infotech. He is a very disciplined, soft spoken and enthusiastic person. Being the founder of the company, he takes care of business development activities and maintains relations with clients.

    His charismatic and result driven approach has benefited the company to grow and achieve this height where the company stands right now. His vision, long term planning and sharp knowledge on latest technologies made this organization so successful and profitable in such a short period of time. Bharat ensures that the company gets up-to-date & latest knowledge on different technologies and trends in this competitive market. His problem solving skills and co- ordination abilities makes him favorable among clients and team members.

    View all posts Bharat Koriya

    Related Posts

    How Raindrops InfoTech excels in mobile-first solutions?

    Bharat Koriya
    In a world where smartphones have become a lifeline for the majority of the population,...
    Read More »

    Top 5 web development agencies in Ahmedabad

    Bharat Koriya
    Top 5 web development agencies in Ahmedabad Kem Cho, Ahmedabad? Stressed about choosing the best...
    Read More »

    Write in to us!

    We are just a click away. Let’s hear from you!