Skip to content

SimpleRandom constructor does not set seed value randomly if $seed is null #6

Description

@pointybeard

Problem
Relates to Random/SimpleRandom class around line 40. The code looks like this:

    public function __construct($seed = null)
    {
        if ($seed === null || $seed === 0) {
            $this->seed(mt_rand());
        }
        
        $this->seed($seed);
    }

Notice that if $seed is either null or 0, that mt_rand() is used to populate the seed value with a random value, however, the following line just overrides that with the contents of $seed (either null or 0).

Current Behaviour
Calling new SimpleRandom() (i.e. without providing a seed value) will produce the same seed value everytime resulting in non-random value being generated (for me it's always int(125)).

Expected Behaviour
Calling new SimpleRandom() will produce a random seed value for use internally.

Solution
Modify the constructor to something like this to ensure the result of calling mt_rand() is propagated:

    public function __construct($seed = null)
    {
        if ($seed === null || $seed === 0) {
            $seed = mt_rand();
        }
        
        $this->seed($seed);
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions