Re: Brainstorming idea: inline syntax for lexical (captured) variables

From: Date: Tue, 14 Mar 2023 22:58:15 +0000
Subject: Re: Brainstorming idea: inline syntax for lexical (captured) variables
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-119701@lists.php.net to get a copy of this message
> I guess you'd have to generate a new class entry every time the "new > class" line was run, and inject the extra values into that. > > > If it was limited to capturing scalars and arrays, you could treat it as > a kind of macro expansion, i.e. this ... > > $example = new class { > public $inner = $^outer; > } > > ... could be a sort of sugar for: > > eval( > sprintf( > 'return new class { > public $inner = %s; > };', > var_export($outer, true) > ) > ); > > Which is valid code, if not particularly efficient: > https://3v4l.org/sQaUS Unfortunately, PHP isn't really well suited for something like that. Eval'd classes are still request-persistent, so any created object would leak its class structure (which is much bigger and less optimized in terms of memory than the object). Normal anonymous classes: https://3v4l.org/41UGH Anonymous classes created through eval (and thus creating a separate class): https://3v4l.org/Q9eE3 Ilija

« previous php.internals (#119701) next »