قالب وردپرس درنا توس
Home / Tips and Tricks / 8 Key New Features in PHP 8 – CloudSavvy IT

8 Key New Features in PHP 8 – CloudSavvy IT



PHP logo

PHP 8 was released at the end of November 2020. It is a major new version that upgrades the language with additional features and performance improvements.

In this article, we’ll take a look at eight of the biggest enhancements offered by PHP 8. The full list of additions and changes can be found in the official documentation. The documents also include a comprehensive migration guide for use when updating projects from PHP 7.4.

1
. Features

Attributes, also called annotations in other languages, provide a mechanism for adding metadata to your codebase. Attributes can be used with classes, methods, functions and properties. They are easier to work with than the docblock approach used by many PHP 7 projects.

Attributes are defined as simple classes, self-annotated with built-in PHP Attribute attribute:

#[Attribute]
class CloudSavvyAttribute {
 
    protected string $value;
 
    public function __construct(string $value) {
        $this ->; value = $value;
    }
 
    public function getValue() : string {
        return $this ->; value;
    }
 
}

They can then be added to entities within your codebase:

#[CloudSavvyAttribute("Example")]
class CloudSavvyClass {
    // ...
}

Attributes are retrieved via the Reflection API. You can inspect and construct attributes defined on a class, method, or other codebase component. Attributes are probably most useful within frameworks and libraries, where they help abstract one-time mapping of app components, such as route definitions and dependency injection threads.

2. Named arguments

Named arguments allow you to pass parameters to methods and functions using an array-like construction. This makes it easier to skip optional parameters and not pass them in the correct order.

function foo(?string $a=null, ?string $b=null, ?string $c=null) : void;

In PHP 7, call the above function while passing the value "demo" to $c required the following call:

In PHP 8 the following syntax can be used instead:

This makes function calls with many optional arguments less repetitive and easier to maintain.

Filling the properties of a class with initial values ​​is one of the most common roles of a constructor. Code similar to the following is common in PHP 7 codebases:

class Example {
 
    protected ?string $Property;
 
    public function __construct(?string $Property=null) {
        $this ->; Property = $Property;
    }
 
}

PHP 8 adds support for Constructor Property Promotion, a shortened syntax that allows you to combine property definition, type hinting, and population inline in the constructor’s signature. The above example could be rewritten as follows:

class Example {
    public function __construct(
        protected string $Property=null
    )
}

This style removes repetition. Using it makes it easier to add additional constructor properties in the future, reducing the number of code sections you need to change.

4. Types of Union

PHP’s type system continues to evolve with PHP 8. It is now possible to designate types as an “union” of two or more types, where the value of the type can be derived from any of the types in the association .

public function foo(string|int $bar) : int|float;

In the above artificial example, the foo() function accepts both strings and integers. It returns an integer or a float.

In practice, this skill is probably most useful when applied to properties and method parameters – it is a good way to accept a variety of input types and normalize to a well-defined single output type.

5. Match expression

The new match expression is a much safer alternative to the known switch. It does not require the use of case and break statements, supports combined conditions and returns a value instead of entering a new block of code. Duress type is disabled, so 1.0 (float) is not considered equivalent to "1.0" (string), unlike when using switch.

Here’s a typical PHP 7 switch:

switch (1.0) {
    case 1.0:
        $result = "Float!";
        break;
    case "foo":
    case "bar":
        $result = "foobar!";
        break;
}

And here’s what the same code could look like with PHP 8:

$result = match (1.0) {
    1.0 =>; "Float!",
    "foo", "bar" =>; "foobar!"
}

Again, the new approach is much more concise. One caveat to note is that syntax values ​​of combined conditions are not defined within an array, but rather as a simple comma separated set, similar to calling a function.

6. The “Nullsafe” operator

Another concept borrowed from other languages, PHP 8 now supports inline zeroing with automatic shorting. You can build a series of checks that will abort and return null, when the evaluation of an element fails.

In PHP 7:

$photo = null;
if ($user !== null) {
    if ($user ->; profile !== null) {
        if ($user ->; profile ->; getPhoto() !== null) {
            $photo = $user ->; profile ->; getPhoto() ->; getPath();
        }
    }
}

And in PHP 8:

$photo = $user? ->; profile? ->; getPhoto()? ->; getPath();

PHP 8 again offers a simpler solution, which makes nesting impossible. This results in significantly less code to test and maintain.

7. Stricter type system

We’ve already looked at how Union Types adds an extra layer of flexibility to the PHP 8 type system. A number of additional changes in this area increase the rigor and consistency with which type checking is enforced.

Comparisons between strings and numbers are now healthier. 0 (integer) is no longer equal to "" (empty string) and equations like 123 == "123abc" now evaluate to false, not true. These changes help reduce the chances of comparison errors in your codebase, although some work may be required to ensure that older projects are compatible.

The type system also has an explicit one mixed type (to indicate that each value is compatible), as well as a static return type (supports late static binding). Elsewhere, abstract methods signatures in properties are now properly verified.

All in all, these changes promote PHP’s support for highly typed programming. Consistent use of type hinting eliminates many of the bugs that can occur in weakly typed languages, giving developers more confidence that the code is functioning as intended.

8. JIT

The last item in our list is more of a behind-the-scenes feature than a language feature. PHP 8 adds support for Just-In-Time compilation support, which has the potential to improve performance significantly.

Long-running scripts hosting repetitive tasks benefit the most from JIT compilation. Benchmarks indicate that the improvement will be less pronounced in web applications, where PHP is most commonly found. However, the addition of the JIT can help PHP expand into other areas of programming, increasing the overall appeal and versatility of the language.

The JIT must be enabled with new settings in it php.ini configuration file. Detailed guidelines on the available values ​​and their effects can be found in the documentation; However, the following is recommended as a general standard:

<code>opcache.enable=1
opcache.jit_buffer_size=100M
opcache.jit=1255code>

Conclusion

We’ve looked at just eight of the most important additions and changes in PHP 8. It’s worth checking the official release notes before using PHP 8 in your projects, as there are many more small features that we haven’t been able to cover here.

While most changes are backward compatible, potential pitfalls include the type of system improvements and changes within the standard library. You can find the full migration guide on the PHP documentation site.


Source link