DEV Community

Brent Roose
Brent Roose

Posted on • Originally published at stitcher.io on

5

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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 :)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more