I'm using AMP ParallelFunctions and AMP Promise wait to create an async execution in PHP. The idea is to call multiple HTTP endpoints simultaneously and wait until all of them are resolved.
The code looks something like this:
$result = wait( parallelMap( $myArray, function($item) use ($api) {
return $api->call_api( $item );
} ) );
The function $api->call_api
lives on a different file and uses a Bearer token from a global constant, it throws the error PHP Warning: Use of undefined constant API_TOKEN
every time it's invoked by the async process (it runs ok as a synchronous process)
I suspect this happens because parallelMap
is a PHP worker that doesn't have access to the same scope where API_TOKEN
was defined.
Any ideas how to make wait and parallelMap to recognize a variable defined by define('API_TOKEN', 'my-value')
?
This issue happens because PHP Thread Workers don't have access to the global scope where constants were defined.
I ended up passing creating a local variable, assigning the global variable to it, and then pass it to the anonymous function, as Sammitch suggested.
Something like this:
$my_global = GLOBAL_CONSTANT;
$result = wait( parallelMap( $myArray, function($item) use ($api, $my_global) {
return $api->call_api( $item, $my_global );
} ) );
This approach as also suggested by people that give maintenance to this package: