Property Hooks

Developers often use methods to wrap and guard access to object properties. There are several highly common patterns for such logic, which in practice may be verbose to implement repeatedly. Alternatively, developers may use __get and __set to intercept reads and writes generically, but that is a sledge-hammer approach that intercepts all undefined (and some defined) properties unconditionally. Property hooks provide a more targeted, purpose-built tool for common property interactions.

class User 
{
    public string $name {
        set {
            if (strlen($value) === 0) {
                throw new ValueError("Name must be non-empty");
            }
            $this->name = $value;
        }
    }
 
    public function __construct(string $name) {
        $this->name = $name;
    }
}

You can play around with them on 3v4l.org

Click the bar to cast your vote!
61%
39%
1

OK

Share:
lloricode avatar
lloricode
voted yes
1

This is one of the reasons why I love C#. Would be a nice addition in PHP!

Share:
woutercypers avatar
woutercypers
voted yes
1

Nice to have!

We already have this kind of properties in C#!

Share:
pentiminax avatar
pentiminax
voted yes
1

It simplifies dedicated logic for setters/getters, without having to mess directly with __get() and __set().

Share:
rinodrummer avatar
rinodrummer
voted yes
1

This would be a very interesting way to ensure values of an property.

Share:
tiago avatar
tiago
voted yes
1

This seems a really nice addition! Love it!

Share:
aplouro avatar
aplouro
voted yes
1

This is long overdue.

Share:
jeffdafoe avatar
jeffdafoe
voted yes
1

cool stuff! think it would be great way to remove validation from the constructor when implementing a value object

Share:
mohammad avatar
mohammad
voted yes
1

That would simplify our lives a lot in the day-to-day tasks like validation, data handling, transformation, etc. Paring this with Attributes can give us a lot of fire power! ;)

Share:
joelpiccoli avatar
joelpiccoli
voted yes
1

It could be used by ORMs like Laravel Eloquent Model that has cast and other hooks to transform data on get/set.

This would be really useful if this hooks could be added externally. So we can use attributes to add generic validation or transformation hooks.

Share:
gromnan avatar
gromnan
voted yes

Check out another RFCs

Short Closures 2.0

This RFC proposes a way to have multi-line short closures — closures that don't need explicit use statements, but can still have multiple lines and a return statement.

101
373 yes
66 no
The Pipe Operator

The "pipe operator" |> allows you to chain multiple function calls in a more convenient way.

93
272 yes
131 no
Asymmetric Visibility v2

A new syntax for declaring the “set” operation visibility of an object property

20
16 yes
42 no
RSS Feed Contribute Watch on YouTube Our License
© 2024 RFC Vote. This project is open source. Contribute and collaborate with us!