On Wed, May 10, 2023, at 11:35 AM, Robert Landers wrote:
>> Regarding $field vs. $this->propName, there's a few reasons we went that 
>> route.
>>
>> 1. It's shorter and less typing for what will be a common pattern.
>> 2. That makes it consistent between hook implementations.  In working on 
>> examples, I found many cases where I was adding basically the same line to 
>> multiple hooks on the same class.  Making the code easier to copy-paste 
>> seems like a win.
>> 3. It also will be helpful if hook packages are added in the future, as 
>> they'll need a more "generic" way to access the backing property.  (See 
>> Future Scope.)  Eg, "$field = someLogic($value)" applied to a dozen 
>> different properties; it wouldn't work if it was "$this->specificProperty = 
>> someLogic($value)".
>> 4. We're used to our eyes glossing over "$this->propName", as it's so 
>> common.  Having a separate name to mentally scan for to determine if a 
>> property is virtual or not seems like it will be helpful in practice.
>> 5. There's precedent for it: Kotlin has almost the same functionality as we 
>> describe here, and uses a `field` variable in the exact same way.
>>
>> So it's mainly an ergonomics argument rather than a technical one.  "Compile 
>> time macro" means it translates to the same AST as if you'd used 
>> $this->propName.  There's precedent for that.  Constructor Property 
>> Promotion works basically the same way.
>
> With using a common name for say, $value, open the door for a library
> of common hook implementations (eventually)?
>
> Maybe something like:
>
> class User {
>   // snip
>   public string $fullName { get => FancyLibrary\fullName(...) }
>   // snip
> }
>
> I could imagine something like this would be a huge boon to PHP if it
> automatically bound the closure.

$field is only available inside the hook itself, not inside functions called 
from it.  But that does mean you could do this instead:

class User {
  // snip
  public string $fullName { get => FancyLibrary\fullName($field) }
  // snip
}

Which, yes, should work fine.

If such a library actually became popular, that would be an argument to 
implement the "property hook packages" or "property traits" concept that Swift 
has, as noted in Future Scope.

--Larry Garfield

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to