Random\Engine::generate

(PHP 8 >= 8.2.0)

Random\Engine::generateGenerates randomness

说明

public Random\Engine::generate(): string

Returns randomness and advances the algorithm’s state by one step.

The randomness is represented by a binary string containing random bytes. This representation allows to unambiguously interpret the random bits generated by the algorithm, for example to accomodate different output sizes used by different algorithms.

Algorithms that natively operate on integer values should return the integer in little-endian byte order, for example by leveraging the pack() function with the P format code. The high-level interface provided by the Random\Randomizer will interpret the returned random bytes as unsigned little-endian integers if a numeric representation is required.

It is strongly recommended that each bit of the returned string is uniformly and independently selected, as some applications require randomness based on the bit-level to work correctly. For example linear congruential generators often generate lower-quality randomness for the less significant bits of the return integer value and thus would not be appropriate for applications that require bit-level randomness.

参数

此函数没有参数。

返回值

A non-empty string containing random bytes.

注意: The Random\Randomizer works with unsigned 64 bit integers internally. If the returned string contains more than 64 bit (8 byte) of randomness the exceeding bytes will be ignored. Other applications may be able to process more than 64 bit at once.

错误/异常

示例

示例 #1 Random\Engine::generate() example

<?php
/**
* Implements a Linear Congruential Generator with modulus 65536,
* multiplier 61 and increment 17 returning an 8 Bit integer.
*
* Note: This engine is suitable for demonstration purposes only.
* Linear Congruential Generators generally generate low
* quality randomness and this specific implementation has
* a very short 16 Bit period that is unsuitable for
* almost any real-world use case.
*/
final class LinearCongruentialGenerator implements \Random\Engine
{
private
int $state;

public function
__construct(?int $seed = null)
{
if (
$seed === null) {
$seed = random_int(0, 0xffff);
}

$this->state = $seed & 0xffff;
}

public function
generate(): string
{
$this->state = (61 * $this->state + 17) & 0xffff;

return
pack('C', $this->state >> 8);
}
}

$r = new \Random\Randomizer(
new
LinearCongruentialGenerator(seed: 1)
);

echo
"Lucky Number: ", $r->getInt(0, 99), "\n";
?>

以上示例会输出:

Lucky Number: 4