简体   繁体   中英

php oop. how to use variable freely?

i having a problem in one of my code. im trying to learn how to do oop, but im stuck in understanding the principle of object.

im try to use variable tht i declare as private, and it predefine. i cant make it defined in function set.

class generateRandomString{
private $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
private $randomString = '';

private function setGenerateRandomString($length = 10){

    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
}
public function getGenerateRandomString(){
    $this->setGenerateRandomString();
    return $this->$randomString;
}
}

and i dont understand either, why there is no clear explanation about this topic in internet about how to use class dynamically? or did i miss it? the tutorial and lesson that i found, all about the same thing, as of how to set, get, variable from out of class. i need help in how to fully utilize the class and function as im more into building a complex self-operate algorithm than building user-interact system.

and im totally new in class. sorry for asking.

In your private set function, you are not referencing the correct variables.

Whenever you reference an object instance variable, you use $this->variableName . So, in your setRandomString( ) function call, you simply need to update the variables to the appropriate instance variables, like so:

private function setGenerateRandomString($length = 10){
    for ($i = 0; $i < $length; $i++) {
        $this->randomString .= $this->characters[rand(0, strlen($this->characters) - 1)];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM