Practice content: randomly generate a string
Code:
<?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) {
$arr 1 = array ();
$arr = Array_rand ($this->two, $this->length);
for ($i =0; $i <count ($arr); $i + +) {
Array_push ($arr 1, $this->two[$arr [$i]]);
}
echo Implode ("", $arr 1);
}else if ($this->type = = 3) {
$arr 1 = array ();
$arr = Array_rand ($this->three, $this->length);
for ($i =0; $i <count ($arr); $i + +) {
Array_push ($arr 1, $this->three[$arr [$i]]);
}
echo Implode ("", $arr 1);
}else{
echo ' parameter Error! ‘;
}
}
}
$randstr = new randstring (10,2);
$randstr->getstring ();
?>
Some functions:
Implode () the array is converted to a string, you can add delimiters
Array_rand () randomly extracts the index of an element within an array, and returns an array of an index if the second argument is added.
Array_push () fills the value into an array
:
PHP Object-oriented practice