dongwuqi4243 2014-09-30 02:17
浏览 33
已采纳

php oop。 如何自由使用变量?

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.

  • 写回答

1条回答 默认 最新

  • duanjie1339 2014-09-30 02:34
    关注

    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)];
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python验证码滑块图像识别
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)