dwerty_weird
dwerty_weird

Reputation: 183

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.

Upvotes: 0

Views: 54

Answers (1)

jeffjenx
jeffjenx

Reputation: 17487

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)];
    }
}

Upvotes: 1

Related Questions