Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php-oop。如何自由使用变量?_Php_Class_Oop - Fatal编程技术网

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

php-oop。如何自由使用变量?,php,class,oop,Php,Class,Oop,我的一个代码有问题。我试图学习如何进行面向对象编程,但我一直在理解对象的原理 我尝试使用我声明为私有的变量tht,它是预定义的。我不能在函数集中定义它 class generateRandomString{ private $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; private $randomString = ''; private function setGenerateR

我的一个代码有问题。我试图学习如何进行面向对象编程,但我一直在理解对象的原理

我尝试使用我声明为私有的变量tht,它是预定义的。我不能在函数集中定义它

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;
}
}
类生成器域字符串{
private$characters='0123456789abcdefghijklmnopqrstuvwxyzabefghijklmnopqrstuvwxyz';
私有$randomString='';
私有函数setGeneratorDomainString($length=10){
对于($i=0;$i<$length;$i++){
$randomString.=$characters[rand(0,strlen($characters)-1)];
}
}
公共函数getGeneratorDomainString(){
$this->setGeneratorDomainString();
返回$this->$randomString;
}
}
我也不明白,为什么互联网上没有关于如何动态使用类的明确解释?还是我错过了?我找到的教程和课程,都是关于如何在课外设置、获取变量的。我需要帮助如何充分利用类和函数,因为im更多地用于构建复杂的自操作算法,而不是构建用户交互系统


我是新来的。很抱歉询问。

在您的私有集函数中,您没有引用正确的变量

每当引用对象实例变量时,都要使用
$this->variableName
。因此,在
setRandomString()
函数调用中,只需将变量更新为适当的实例变量,如下所示:

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

$this->characters
$this->randomString
,没有额外的
$
符号,我尝试了“$characters=$this->$characters;”和“$randomString=$this->$randomString;”。有错吗?@dwerty_-weird仔细阅读,箭头后没有$符号。@dwerty_-weird:现在请再次阅读我的评论。我没有检查代码或将其重写以进行优化,只是对其进行了修改-例如,第二次后续请求将不会删除
随机字符串中的数据