PHP面向对象练习
练习内容:随机生成一个字符串
代码:
<?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() 将数值填入到一个数组中
效果图: