DEV Community

Discussion on: PHP Typed Properties: Think Twice.

Collapse
 
nicolus profile image
Nicolas Bailly

Typed property doesn't mean you should suddenly expose your properties as public and forego getters and setters ! These are two unrelated issues IMHO. What typed properties will allow you to do is replace

/**
 * @var int
 */
private $price;

with

private int $price;

With the added bonus that it won't be only interpreted by your IDE but also trigger an error if you try and use something that's not a integer when using $price inside your class.

Now if you want to avoid using getters and setters for every single property but still maintain the ability to add validation/mutators/accessors later on, there's an old RFC that would solve this issue by using C# style getters and setters : wiki.php.net/rfc/propertygetsetsyntax

Collapse
 
okdewit profile image
Orian de Wit • Edited

Exactly! Docblocks have always been an abomination in my opinion, abusing PHP's metaprogramming flexibilities to create incomplete static analysis tooling for something that needs to be in the language itself.

A comment should be used to communicate to fellow humans, not to tools — that's what the rest of the syntax is for.

First we got parameter & return type hints, which made docblocks much less necessary. I see typed properties as the next major step to liberate us from ugly syntax.

But indeed, whether to use protected /get/set or public is completely unrelated to typed properties.

In many cases, protected fields are advisable.

The difference is that IF you use a public property somewhere (I use them commonly on simple DTO classes), or if a setter method does some (slightly too complicated) mutation, you now get some extra safety...