Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

PHP 7.4 will support first-class property type declarations

With the introduction of scalar type declaration and return type declaration in PHP 7.0, the language’s type system got improved at some extent. Although it’s great to have some layer of strictness, it’s still missing the support to declare typed properties. But from PHP 7.4, it seems, it’s going to change because according to this accepted RFC, PHP 7.4 will be getting support for first-class property type declarations.

Without the typed properties, you have to use getter and setter methods in order to enforce strict types on the class properties like below:

class Post 
{    
    private $id;

    private $title;
 
    public function __construct(
        int $id, 
        string $title
    ) 
    {
        $this->id = $id;
        $this->title = $title;
    }
 
    public function getId(): int 
    {
        return $this->id;
    }

    public function setId(int $id): void 
    {
        $this->id = $id;
    }
 
    public function getName(): string 
    {
        return $this->name;
    }

    public function setName(string $name): void 
    {
        $this->name = $name;
    }
}

But with the introduction of typed properties, you’ll no longer require additional methods just to ensure the type-safety of properties. This means writing less code and more performance gain. The above code would be reduced to this without loosing type-safety of the properties:

class Post 
{    
    private int $id;

    private string $title;
 
    public function __construct(
        int $id, 
        string $title
    ) 
    {
        $this->id = $id;
        $this->title = $title;
    }
}

Learn more about this here: https://wiki.php.net/rfc/typed_properties_v2

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?