Re: Is it possible to add asynchronous loop call function ?

From: Date: Fri, 24 Nov 2023 10:26:54 +0000
Subject: Re: Is it possible to add asynchronous loop call function ?
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-121800@lists.php.net to get a copy of this message
Hi Robert, pt., 24 lis 2023 o 10:24 Robert Landers <landers.robert@gmail.com> napisał(a): > ... > You can also emulate this with: > > class Defer { > private function __construct(private \Closure $callback) {} > public function __destruct() { $this->callback(); } > public static function _(\Closure $callback) { return new > self($callback); } > } > > and use it like: > > function writeSomeStuff() { > // open files > $deferred = Defer::_($closeFiles(...)); > // do stuff > } > > So long as a reference exists to $deferred variable, the deferred > method won't be run. If the variable is local to the method/function > being run it, the deconstructor will be called after the function > returns. > > It isn't the most beautiful thing in the world, and easy to forget to > store the result of Defer, but it is handy sometimes. > This is interesting which makes me thinking if forget to store it could be prevented. I think requiring a ref could help with that: class Defer { private function __construct(private \Closure $callback) {} public function __destruct() { ($this->callback)(); } public static function _(\Closure $callback, &$var) { $var = new self($callback); } } $deferred = Defer::_($closeFiles(...), $foo); Without $foo there'd be an ArgumentCountError. Cheers, Michał Marcin Brzuchalski

« previous php.internals (#121800) next »