Re: PHP True Async RFC - Stage 2

From: Date: Fri, 21 Mar 2025 10:03:50 +0000
Subject: Re: PHP True Async RFC - Stage 2
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-126884@lists.php.net to get a copy of this message
Good day, everyone. As I write more code examples, I'm starting to get annoyed by the verbosity of the spawn in $scope construct—especially in situations where all spawns need to happen within the same context. At the same time, in 80% of cases, it turns out that explicitly defining $scope is the only correct approach to avoid shooting yourself in the foot. So, it turns out that the spawn in $scope construct is used far more frequently than a plain spawn. I remembered an example that Larry came up with and decided to use it as syntactic sugar. There’s some doubt because the actual gain in characters is minimal.. This block doesn't change the logic in any way. The convenience lies in the fact that within the block, it’s clear which $scope is currently active. However, this is more about visual organization than logical structure. Here's what I ended up with: ### Async blocks Consider the following code: ```php function generateReport(): void { $scope = Scope::inherit(); try { [$employees, $salaries, $workHours] = await Async\all([ spawn in $scope fetchEmployees(), spawn in $scope fetchSalaries(), spawn in $scope fetchWorkHours() ]); foreach ($employees as $id => $employee) { $salary = $salaries[$id] ?? 'N/A'; $hours = $workHours[$id] ?? 'N/A'; echo "{$employee['name']}: salary = $salary, hours = $hours\n"; } } catch (Exception $e) { echo "Failed to generate report: ", $e->getMessage(), "\n"; } } ``` with async ```php function generateReport(): void { try { $scope = Scope::inherit(); async $scope { [$employees, $salaries, $workHours] = await Async\all([ spawn fetchEmployees(), spawn fetchSalaries(), spawn fetchWorkHours() ]); foreach ($employees as $id => $employee) { $salary = $salaries[$id] ?? 'N/A'; $hours = $workHours[$id] ?? 'N/A'; echo "{$employee['name']}: salary = $salary, hours = $hours\n"; } } } catch (Exception $e) { echo "Failed to generate report: ", $e->getMessage(), "\n"; } } ``` #### async syntax ```php async <scope> { <codeBlock> } ```

« previous php.internals (#126884) next »