PHP 将随机单词存储在字符串中以多次使用


PHP store random word in string to use multiple times

public function generateRandomString($length = 16) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
         $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

我正在寻找一种将其存储在变量中的方法。例如:$random = $this->generateRandomString();并一遍又一遍地使用此变量,而不会更改值。我该怎么做?

在类中创建一个属性:

Class MyClass {
   private $myRandomString;
   public function generateRandomString($length = 16) {
       $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
       $charactersLength = strlen($characters);
       $randomString = '';
       for ($i = 0; $i < $length; $i++) {
         $randomString .= $characters[rand(0, $charactersLength - 1)];
       }
       return $randomString;
    }
    public function generate() {
         $this->myRandomString = $this->generateRandomString();
    }
    public function fetchRandomString(){
         return $this->myRandomString;
    }
}
$myClass = new MyClass(); 
$myClass->generate(); //Puts the random value in `private $myRandomString`
$myValue = $myClass->fetchRandomString(); //Returns the random string created
$myAnotherValue = $myClass->fetchRandomString(); //Returns the random string created (still same value)

以下是函数调用较少的修订版本。

class NumberGenerator {
   private $length = 16;
   private $myRandomString = null;
   function __construct($length){
     $this->length = $length;
   }
   public function generateRandomString() {
       $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
       $charactersLength = strlen($characters);
       $randomString = '';
       for ($i = 0; $i < $this->length; $i++) {
         $randomString .= $characters[rand(0, $charactersLength - 1)];
       }
       return $randomString;
   }
    public function fetchRandomString(){
        if($this->myRandomString === null){
           $this->myRandomString = $this->generateRandomString(); 
        }
         return $this->myRandomString;
    }
}

//usage
$myClass = new NumberGenerator (16); 
$randomStr = $myClass->fetchRandomString();
echo $randomStr;      //example output: CqaLEYILzxLbWPDw