DEV Community

Brent Roose
Brent Roose

Posted on • Originally published at stitcher.io on

Typed properties in PHP

Typed class properties were added in PHP 7.4 and provide a major improvement to PHP's type system.These changes are fully opt-in and backwards compatible.

In this post we'll look at the feature in-depth, but first let's start by summarising the most important points:

  • Typed properties are available as of PHP 7.4
  • They are only available in classes and require an access modifier: public, protected or private; or var
  • All types are allowed, except void and callable

This is what they look like in action:

class Foo
{
    public int $a;

    public ?string $b = 1;

    private Foo $prop;

    protected static string $static = 'default';
}

If you're unsure about the added benefit of types, I'd recommend you reading this post first.

Continue reading about the ins and outs of typed properties on https://stitcher.io/blog/typed-properties-in-php-74#uninitialized

Top comments (2)

Collapse
 
aleksikauppila profile image
Aleksi Kauppila

Are you sure nullable string can be 1?

Collapse
 
brendt profile image
Brent Roose

That was a type and fixed now :)