New Typed Properties in PHP 7.4

New Typed Properties in PHP 7.4

Typed properties in PHP

After not great start in 2011, there is a finally confirmed Class Typed Properties to be introduced in 7.4 version. These properties could be of any available type (apart from callable and void) and introduce some limitation when using inheritance to prevent from changing the types in child’s class.

This will include any static properties as well as usage of ? mark to inform that the variable could be also a NULL value.

class MyTypedClass {
    public int $scalarType;
    protected ClassName $classType;
    private ?ClassName $nullableClassType;
 
    // available to static
    public static iterable $staticProp;
 
    // default values
    public string $str = "foo";
    public ?string $nullableStr = null;
 
    // usage for many vars in single line
    public float $x, $y;
}

//inheritance limitations:
class First {
    private bool $a;
    public int $b;
    public ?int $c;
}
class Second extends First {
    public string $a; // all fine as First::$a is private
    public ?int $b;   // error
    public int $c;    // error
}

There is also a plan to introduce support of multiple types called: Union Types, which would allow to provide a list of combined types for the single var, for instance:

class MyClass {
    public int|string $a;
    public array|string $b;
}

However this is marked as pending work for future whereas the Typed Properties are something which prototype already exists.

Reference

PHP 7 News & Updates v7.0 - 7.4 - Book coverPHP 7 News & Updates v7.0 – 7.4 Book https://www.amazon.com/PHP-News-Updates-v7-0-7-4/dp/1727202481/

Rate this artcile
[Total: 1 Average: 5]