Adam Biro

Software Developer

Blogger

Photographer

Full Stack Developer

Photo Enthusiast

Web Developer

Adam Biro
Adam Biro

Software Developer

Blogger

Photographer

Full Stack Developer

Photo Enthusiast

Web Developer

Blog Post

[3] New PHP8 Constructor property promotion, static return, mixed type features

April 7, 2022 IT, PHP, Programming
[3] New PHP8 Constructor property promotion, static return, mixed type features

PHP 8.0 release date was on Nov 26, 2020. Because of this, it brought several new interesting features to our life. This is the third part of the series and in the current post, I want to go through the Constructor property promotion, New static return type, and New mixed type. You can see the full list of features here. Furthermore, you can read the second part of the series here.

Constructor property promotion

Constructor Property Promotion is syntactic sugar. It helps to reduce the code. We do not have to define separately the class property and the assignment sections. We can do this with a simple code and PHP transform our code to the familiar syntax under the hood before the execution. So instead of writing the following code:

class Money 
{
    public Currency $currency;
 
    public int $amount;
 
    public function __construct(
        Currency $currency,
        int $amount,
    ) {
        $this->currency = $currency;
        $this->amount = $amount;
    }
}

We can write this one and it will be converted to the code above before the code start running.

class Money 
{
    public function __construct(
        public Currency $currency,
        public int $amount,
    ) {}
}

New Static Return Type

We could already return self but returning static was not a valid return type until PHP 8. But in the new version of PHP we will be able to do this:

class Foo
{
    public function test(): static
    {
        return new static();
    }
}

New Mixed Type

When the type of the returning data depends on a condition then the IDE generates a mixed return type in the dock block section. PHP 8 introduces the Mixed type into the language as an option. Due to this Mixed type can be one of the following types: array, bool, callable, int, float, null, object, resource, string.

Mixed can also be used as a parameter or property type, not just as a return type. Since mixed already includes null, it’s not allowed to make it nullable. The code below will trigger an error:

// Fatal error: Mixed types cannot be nullable, null is already part of the mixed type. function bar(): ?mixed {}

Useful Topic related Links:

New in PHP 8

Taggs:
Write a comment