Home > Back-end >  Can a php application instantiate multiple RNGs
Can a php application instantiate multiple RNGs

Time:01-04

Update - this question applies to PHP < 8.2 - for 8.2 , You have access to Randomizer


PHP supports `mt_rand()` and `mt_srand()`, but these are global and static.

I notice in the PHP C source that mt_rand uses a engine_mt19937 instance; is there a way in PHP to instantiate our own instance of this RNG so we can control its seed?

CodePudding user response:

is there a way in PHP to instantiate our own instance of this RNG so we can control its seed?

With PHP 8.2 , yes. See the \Random classes. You can do something like:

$rand1 = new \Random\Engine\Mt19937($seed1);
$value1 = $rand1->generate();

$rand2 = new \Random\Engine\Mt19937($seed2);
$value2 = $rand2->generate();

CodePudding user response:

On PHP 8.2 , yes. See @AlexHowansky's answer for that. On earlier PHP versions, no.

Your link to the source code points to the master branch, which already has the PHP 8.2 logic in it since it was officially released last month. That is why the master branch includes the reference to an MT19937 engine.

On older versions (e.g. the latest 8.1 branch) you can see that mt_rand() did not use a configurable engine but just checked if it was already seeded. PHP 8.1 and earlier used a single global generator for mt_rand() so it is not possible to have multiple RNGs with different seeds if you want to use the native functions.

Having said that, you could probably roll your own implementation of an MT19937 RNG for PHP 8.1. Others have.

  •  Tags:  
  • php
  • Related