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
orprivate
; orvar
- All types are allowed, except
void
andcallable
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)
Are you sure nullable string can be 1?
That was a type and fixed now :)