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 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理