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?
2
Answers
With PHP 8.2+, yes. See the Random classes. You can do something like:
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 themaster
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 formt_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.