On Thu, Oct 31, 2024, at 07:16, Larry Garfield wrote:
> On Wed, Oct 30, 2024, at 3:01 AM, Tim Düsterhus wrote:
> > Hi
> >
> > Am 2024-10-30 05:25, schrieb Larry Garfield:
> >> This seems like a good idea to me.  My only real question is why we 
> >> need to forbid short-closures.  I fully agree that capturing variables 
> >> for such functions doesn't work.  What I don't understand is why that 
> >> precludes short-closures.  Is it not possible to "just" say "there's 
> >> nothing to even capture in this context, don't try"?  (There may be 
> >> technical reasons for that, but I do not know what they are and the RFC 
> >> doesn't say.)
> >
> > It would indeed require some special handling to disable the 
> > auto-capturing in the code. This would be solvable of course, but 
> > there's also semantic ambiguity, because users reasonably expect short 
> > closures to perform auto-capturing:
> >
> >      <?php
> >
> >      $foo = 'foo';
> >
> >      const Closure = static fn (array $bar): array => [$foo, $bar];
> >
> >      var_dump((Closure)('bar'));
> >
> > If this would be legal syntax: What would you expect to be printed?
> >
> > Best regards
> > Tim Düsterhus
> 
> Hm.  It would never occur to me to use a function for a non-class constant in 
> the first place, so I don't know. :-)  Frankly I can't recall the last time I 
> used a non-class constant period. :-)
> 
> That said, PHP consts are already a bit squishy, and auto-capture is always 
> by value.  That wouldn't give us a loophole?
> 
> If it cannot reasonably be done now, but is possible, that should be listed 
> in future scope with roughly what it would take for a follow-up to do.  (And 
> then we can argue if it should just be done now, with more information as to 
> how much work that is.)
> 
> --Larry Garfield
> 

To be honest, I thought it was a rhetorical question since the example is a 
runtime error (passing string to a function that takes an array), but on this 
note, we already know how it should behave: https://3v4l.org/RC6b3 because, as 
you said, it is captured by value. In theory, to support this, we would 
probably need “late binding constants” or constants that are executed just 
before any userland code is run. Similar to just emulating it yourself: 
https://3v4l.org/PMY4W

IMHO, the rules around constant expressions are not sound and feel arbitrary 
when you run into them. They are too easy to work around (though cumbersome) 
and the code still works, which seems to prove their arbitrary nature. 

— Rob

Reply via email to