標籤:this array 內容 產生 對象 string 代碼 const 元素
練習內容:隨機產生一個字串
代碼:
<?php
class randstring{
private $length;
private $type;
private $one = array(0,1,2,3,4,5,6,7,8,9);
private $two = array(0,1,2,3,4,5,6,7,8,9,‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘,‘h‘,‘i‘,‘j‘,‘k‘,‘l‘,‘m‘,‘n‘,‘o‘,‘p‘,‘q‘,‘r‘,‘s‘,‘t‘,‘u‘,‘v‘,‘w‘,‘x‘,‘y‘,‘z‘);
private $three = array(‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘,‘h‘,‘i‘,‘j‘,‘k‘,‘l‘,‘m‘,‘n‘,‘o‘,‘p‘,‘q‘,‘r‘,‘s‘,‘t‘,‘u‘,‘v‘,‘w‘,‘x‘,‘y‘,‘z‘,0,1,2,3,4,5,6,7,8,9,‘A‘,‘B‘,‘C‘,‘D‘,‘E‘,‘F‘,‘G‘,‘H‘,‘I‘,‘J‘,‘K‘,‘L‘,‘M‘,‘N‘,‘O‘,‘P‘,‘Q‘,‘R‘,‘S‘,‘T‘,‘U‘,‘V‘,‘W‘,‘X‘,‘Y‘,‘Z‘);
function __construct($l,$t){
$this->length = $l;
$this->type = $t;
}
public function getString(){
if($this->type == 1){
$arr = array_rand($one,$this->length);
$string = explode("",$arr);
return $string;
}else if($this->type == 2){
$arr1 = array();
$arr = array_rand($this->two,$this->length);
for($i=0;$i<count($arr);$i++){
array_push($arr1,$this->two[$arr[$i]]);
}
echo implode("",$arr1);
}else if($this->type == 3){
$arr1 = array();
$arr = array_rand($this->three,$this->length);
for($i=0;$i<count($arr);$i++){
array_push($arr1,$this->three[$arr[$i]]);
}
echo implode("",$arr1);
}else{
echo ‘參數錯誤!‘;
}
}
}
$randstr = new randstring(10,2);
$randstr->getString();
?>
一些函數:
implode()講數群組轉換為字串,可添加分隔字元
array_rand() 隨機抽取數組內元素的索引,如果加入第二個參數,則返回一個索引組成的數組。
array_push() 將數值填入到一個數組中
:
PHP物件導向練習