php学习:随机数(构造函数)

<?php
header("Content-Type:text/html;charset=UTF-8");

//产生随机数

class RandString{


    private $length;   //随机数的长度
    private $type;   //随机数的类型
    //type:1 => 就是数字的随机数
    //type:2 => 就是字母的随机数
    //type:3 => 就是数字+字母的随机数


    public function __construct($length,$type){
        $this->length = $length;
        $this->type = $type;
    }

    public function randNum(){
        switch ($this->type){
            case 1:
                return join(array_rand(range(0,9),$this->length));
                break;
            case 2:
                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;
        }
    }


}


$strNum1 = new RandString(4, 1);   //类型1:数字随机数

echo $strNum1->randNum();

echo '<hr/>';

$strNum2 = new RandString(4, 2);  //类型1:字母随机数

echo $strNum2->randNum();

echo '<hr/>';

$strNum3 = new RandString(4, 3);   //类型1:数字+字母组合随机数

echo $strNum3->randNum();


?>

效果:


猜你喜欢

转载自blog.csdn.net/qq_32584661/article/details/80519630