class RandomString{ //成员属性 private $length; private $type; public function __construct($type=1,$length=4) { $this->length=$length; $this->type=$type; } //成员方法 public function getRandomString(){ switch ($this->type){ case 1: return join(array_rand(range(0,9),$this->length)); break; case 2: //array_merge连接两个数组 //array_flip将数组的键名和键值互换 return join(array_rand(array_flip(array_merge(range('a','z'),range('A','Z' ))),$this->length)); break; case 3: return join(array_rand(array_flip(array_merge(range(0,9 ),range('a','z'),range('A','Z' ))),$this->length)); break; } } } $str1=new RandomString(3,7); echo $str1->getRandomString();