簡體   English   中英

PHP 類隨機數

[英]PHP Class random number

我想做的事:

生成將傳遞給類中的函數的單個隨機數。

換句話說,在調用 $this->random 時 one() 和 two() 都應該返回相同的值

實際發生的事情:

我有多個隨機數,因為 rand() 被多次調用

重要筆記:

我想避免在會話或 SQL 中存儲數字

我的代碼看起來如何:

    class Install
    {
        private $random= '';

        public function __construct()
        {
            $this->random = rand(pow(10, 4-1), pow(10, 4)-1);

        }

         public function one()
         {
           echo $this->random; //example value = 3304
         }

         public function two()
         {
           echo $this-random; //example value = 2504
         }

    }

如果您只想在對同一請求中同一實例的兩個函數調用中使用一致的隨機數,那么您的代碼將按原樣運行。

如果您只想在不同請求中同一實例的兩個函數調用中獲得一致的隨機數,那么您需要使用某種形式的持久存儲,如會話或數據庫。

如果您只想在對同一請求中不同實例的兩個函數調用中使用一致的隨機數,那么您需要一個類靜態變量。

class StaticRandom {
    private static $rand = NULL;

    public static function getRand() {
        if( is_null(self::$rand) ) {
            // this is also where you wouldput the session/DB bits if you
            // want to persist across requests.
            self::$rand = rand(pow(10, 4-1), pow(10, 4)-1);
        }
        return self::$rand;
    }

    public function instanceMethodOne() {
        return self::getRand();
    }

    public function instanceMethodTwo() {
        return self::getRand();
    }
}

$a = new StaticRandom();
$b = new StaticRandom();

var_dump(
    $a->instanceMethodOne(),
    $b->instanceMethodTwo()
);

輸出:

int(4188)
int(4188)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM