Skip to content

PHP Random String Generator Class, OOP.

Share Button
 <?php

class GenerateRandom{
    
    /** Variable to be used by methods */
    public $randomString = '';
    public $lenght;
    public $characters;
    public $charactersLength;
    
    /** Set Length of the random string */
    private function setLength(){
        return $this->length=15;
    }
    
    /** Return Length of the random string */
    public function getLength(){
        return $this->setLength();
    }
    
    /** Set Range of characters to be used for random string */ 
    private function setCharacters(){
        $this->characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        return $this->characters;
    }
    
    /** Return Range of characters to be used for random string */ 
    public function getCharacters(){
        return $this->setCharacters();
    }
    
    /** Return Length of the characters Range string */
    public function getCharactersLength(){
        return  strlen($this->getCharacters());
    }
    
    /** Generate Random string utilizing all above methods */
    public function generateString(){
        /** Loop through Range of characters, choose random charackter 
        *   and add it to $this->randomString.
        *   Repeat it till $i reaches value of $this->getLength()
        */
        for($i=0; $i < $this->getLength(); $i++){
            $this->randomString .= $this->getCharacters()[rand(0, $this->getCharactersLength())];
        }
        /** Return random string */
        return $this->randomString;
    }   
} // Class End


/** Create Class instance */
$getRandom = new GenerateRandom();

/** Call generateString() which will print X-long randon string */
echo $getRandom->generateString();

?>

 

Result of 5 Randomly generated Strings:

PHP Random String Generator Class, OOP.

Share Button