PHP Typed Properties: Think Twice.

Rasmus Schultz on January 12, 2019

The Typed Properties RFC for PHP has been merged to master, and will be available in PHP 7.4. 😍 But, before you pounce on this feature... [Read Full]
markdown guide
 

Both of these examples are flawed.

First, you shouldn't be using public fields. Full stop. It breaks encapsulation, leaks implementation details of the class, and means your class can find itself in an unknown or inconsistent state at any time due to outside influence.

Php doesn't offer properties like C# and other languages, which are really just shorthand for getters and setters. Which is the preferred pattern for exposing private fields.

And to address your point about "double type checking". That's EXACTLY what you're getting. Php only checks types at the compilation stage for typed arguments and returns. Type hints offer no such safety. And even if they did, should you forget the type hint, php will happily let you assign an argument typed as a string into a field you meant to be an int. With the typed field, that's no longer possible.

And your argument for not being able to add additional constraints is also flawed. It has nothing to do with interfaces themselves, just bad interface design. Again, it's the breaking encapsulation and exposing direct fields which causes the problems you bring up. It has nothing to do with typed fields.

There's no "trade off" to be had with typed fields. There's just good code and bad code. And this is bad code.

 

Both of these examples are flawed.

It's all one example, going through iterations with changing requirements.

First, you shouldn't be using public fields. Full stop. It breaks encapsulation, leaks implementation details of the class, and means your class can find itself in an unknown or inconsistent state at any time due to outside influence.

By design. (Outside influence is what's desired with a mutable model.)

The initial requirement is that price be an integer and description be a string, both being mutable.

The first and second code sample equally satisfy those requirements.

Php doesn't offer properties like C# and other languages, which are really just shorthand for getters and setters. Which is the preferred pattern for exposing private fields.

In C#.

But as you pointed out, PHP doesn't offer accessors.

The preferred (only) pattern in PHP at the moment is getter/setter methods - and we're now getting an alternative (public, type-hinted properties) which can satisfy the requirements of the first example, but can't satisfy the new requirements (abstraction, validation) introduced in the following examples.

And to address your point about "double type checking". That's EXACTLY what you're getting.

The point was, if the input to setPrice() has already been type-checked, you don't need the extra type-check when setting the property - your class is already safe from incorrect mutation.

(If you want an extra layer of safety against bugs in your own implementation, sure, a type-hinted private field provides that extra safety. Personally, I'm getting that guarantee from static analysis already with a doc-block.)

Php only checks types at the compilation stage for typed arguments and returns. Type hints offer no such safety.

Did you mean doc-blocks?

PHP checks all static type-hints at run-time, including property type-hints introduced by the RFC. (It's an interpreted language - there's no compilation stage during which assignments could be checked for correctness.)

And your argument for not being able to add additional constraints is also flawed. It has nothing to do with interfaces themselves, just bad interface design. Again, it's the breaking encapsulation and exposing direct fields which causes the problems you bring up. It has nothing to do with typed fields.

There's no "trade off" to be had with typed fields.

There is in the example I used.

It's very likely a lot of PHP developers were excited about this feature so they could simplify models with trivial constraints in this manner.

There are other articles out there already presenting exactly this opportunity with very similar examples.

The point of this article was to make sure these people understand the trade-offs they're making in terms of being able to iterate to meet new requirements.

There's just good code and bad code. And this is bad code.

It seems you read the article making your own assumptions about the requirements for each example. The code in these examples satisfy the requirements for each of those examples at the time - the point was to illustrate how simple requirements often change towards more complex requirements.

You seem to be angry or offended about something, I'm not exactly sure what?

I think for the most part you've just completely misunderstood what I'm trying to say with this article. As mentioned, there are already other articles proposing the kind of change in the first example - in fact, it's similar to the example shown in the RFC itself.

I'm just trying to help people understand the consequences of making such a change.

 

"First, you shouldn't be using public fields."

It is cargo-cult that every OOP programmer has followed since eons.

For example.

public $field;

versus

private $field;
public setField($value) {$this->field=$value;}
public getField() {return $this->field;}

What it's the gaining of private versus public: nothing but more code!.

 

I second that!

Context is key here. There are objects in our daily life that are just a way to organise data. DTO's, entities and such. The integrity of those objects should be made sure from the outside anyway.

And then there are objects whose inner state is critical. It's objects where you might only want to expose properties via constructor and getters to control the state.

However, both types don't really justify hiding protected or private properties behind getters and setter that don't do anything else but to expose said properties as if they were public in the first place.

 

no, you've gained the option of doing anything else at the point of get and set - you can change your implementation - you can refactor your field into something different and maintain your existing interface. a public field is just that, once its there you can never remove it.

In my experience, to hide logic in the getter or setter is dangerous because nobody would expect something there (unless it is a visual object such a button or textbox). So, finally, the getter and setters are a dummy.

Proof, C# has properties, they are a dummy but they are short & easy to write.

int MyProp {set; get;}

 

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

 

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...

 

Isn't the first example breaking the Encapsulation principle of OOP? I rarely ever use public properties, they are almost always protected or in some cases private.

I'd put these interfaced properties that you propose in Abstract classes rather than in Interfaces. Makes more sense in my opinion, Interfaces should stay stateless and remain the messaging contract. :)

 
 

An excerpt from the article:

In the glossary of Design Patterns, Gamma et al., encapsulation is defined as "The result of hiding a representation and implementation in an object..."
So such luminaries as Gamma et al. and the designers of C++ (and Java) are wrong!?
Clearly that there are two definitions of encapsulation, but both valid. It's common for the same word to have different meanings in different communities or contexts. It is not meaningful to say one definition is correct and the other wrong.

 

You can call it however you want but if another object can directly (on properties) change the state of your object, that object is not encapsulated :)

 

If we read this article carefully, we can see that the first example does not really break the principle of encapsulation. The first example shows two non typed properties with getters and setters, but theses ones doesn't provide any validation on the value defined by the user, they only provide type checking. The same type checking provided with public typed properties. Or the principle of encapsulation is to hide class implementation and control the state of the object, since the user can do anything stupid. When I see this it's just like C# auto-properties (a property with an empty getter and setter), it's a language concept.

Now for my opinion, this feature will make more senses if we can use embedded accessors like in the last example, so, interfaces declare properties like:

interface ProductInterface
{
    public int $price { get; }
    public string $description { get; set; }
} 

So it will be the property itself which will provide encapsulation (again, like C# does).

But for now it remains a dream, but it will surely be a great feature, and have a ton of use cases, like for my ORM for example, which will allow the user to give an explicit type for properties mapped to database table columns.

 

You can still get the benefits of type-checking internally though, right?

This is where it will shine. I don´t write setters, so changes internally will be written directly to the property.

It´s so strange that the RFC also has example with public properties. What an awful thing to recommend.

 

It´s so strange that the RFC also has example with public properties. What an awful thing to recommend.

I don't think it's meant as a recommendation or "good practice" - I'm pretty sure the folks behind this RFC know what they're doing. This was probably just the first, most simple example that came to mind, in order to illustrate how the feature would work.

But yeah, clearly the community seem to have jumped to that conclusion - that was my motivation for writing this article 🙂

code of conduct - report abuse