<? |
02 |
|
03 |
/* |
04 |
* 生成随机字符串的类,默认只包含数字、大小写字母 |
05 |
* @author Jerry <maolyc@gmail.com> |
06 |
*/ |
07 |
|
08 |
class randomString { |
09 |
/* |
10 |
* 生成的字符串包含的字符设置 |
11 |
*/ |
12 |
|
13 |
const NUMERIC_ONLY = 1; //只含有数字 |
14 |
const LETTER_ONLY = 2; //只含有字母 |
15 |
const MIXED = 3; //混合数字和字母 |
16 |
|
17 |
/* |
18 |
* 用户传入变量,分别为字符串长度;包含的字母;是否包含大写字母 |
19 |
*/ |
20 |
|
21 |
protected $length, $type, $upper; |
22 |
|
23 |
/* |
24 |
* 参数初始化 |
25 |
* @param int,$length 字符串长度 |
26 |
* @param const,$type 生成字符串的类型 |
27 |
* @param boolean,$upper 是否含有大写字母 |
28 |
*/ |
29 |
|
30 |
public function __construct($length = 16, $type = self::MIXED, $upper = true) { |
31 |
$this->length = $length; |
32 |
$this->type = $type; |
33 |
$this->upper = $upper; |
34 |
} |
35 |
|
36 |
/* |
37 |
* 对象被转化为字符串时调用 |
38 |
* @return string |
39 |
*/ |
40 |
|
41 |
public function __toString() { |
42 |
return $this->pickUpChars(); |
43 |
} |
44 |
|
45 |
/* |
46 |
* 生成随机字符串 |
47 |
* @global $type |
48 |
* @return string,$string |
49 |
*/ |
50 |
|
51 |
public function pickUpChars() { |
52 |
switch ($this->type) { |
53 |
case self::NUMERIC_ONLY: |
54 |
$raw = '0123456789'; |
55 |
break; |
56 |
case self::LETTER_ONLY: |
57 |
$raw = 'qwertyuioplkjhgfdsazxcvbnm' . |
58 |
'QWERTYUIOPLKJHGFDSAZXCVBNM'; |
59 |
break; |
60 |
|
61 |
default: |
62 |
$raw = 'qwertyuioplkjhgfdsazxcvbnm' . |
63 |
'QWERTYUIOPLKJHGFDSAZXCVBNM' . |
64 |
'0123456789'; |
65 |
break; |
66 |
} |
67 |
$string = ''; |
68 |
for ($index = 0; $index < $this->length; $index++) |
69 |
$string .= substr($raw, mt_rand(0, strlen($raw) - 1), 1); |
70 |
if (!$this->upper) |
71 |
$string = strtolower($string); |
72 |
return $string; |
73 |
} |
74 |
|
75 |
} |
76 |
|
77 |
//echo new randomString(170, randomString::MIXED, TRUE).'<br/>'; |