user2531657
user2531657

Reputation: 453

How to use constants inside Amp\parallelMap in PHP?

I need some help with using global constants inside amp\parallelMap. I have a bootstrap file that I require_once in my project, where I define global constants like MAX_DATA.

Here's a simplified version of my code:

$pool = new DefaultPool(self::THREAD_COUNT);

$results = wait(parallelMap($data, function ($point) {
   return $this->reCalc($point); // some time-intensive task
}, $pool));

The reCalc method requires access to the global constant MAX_DATA, but I am unable to access it inside the closure passed to parallelMap. I get an error "Undefined constant MAX_DATA".

The only solution I found is to define the constant again within the closure, or to include the bootstrap file again:

$max = MAX_DATA;

$pool = new DefaultPool(self::THREAD_COUNT);

$results = wait(parallelMap($data, function ($point) use ($max) {
   if (!defined('MAX_DATA')) define('MAX_DATA', $max);
   
   return $this->reCalc($point); // some time-intensive task
}, $pool));

Is there a better way to access global constants inside the closure passed to parallelMap without redefining them?

Upvotes: 0

Views: 48

Answers (0)

Related Questions