【问题标题】:PHP Variable giving "Undefined property:" errorPHP 变量给出“未定义的属性:”错误
【发布时间】:2014-08-15 13:58:29
【问题描述】:

我创建了一个名为 Functions 的类,它存储 3 个公共变量($var1、$var2、$var3)。我有一个 for 循环,它创建该类的一个对象,更新该类的变量,然后将该对象添加到一个数组中。但是,当我尝试访问该数组时,我收到一个错误“未定义的属性:Functions::$InsertTextHere”。

奇怪的是,如果我检查 [$i] 处的数组,它不会播放错误,只有当我检查在先前迭代中创建的数组中的其他任何地方时。例如,for 循环内的 echo 不会引发错误,但 for 循环外的 echo 会。

对不起,如果这很难理解,请告诉我。

class Functions{

    public $var1 = "";
    public $var2 = "";
    public $var3 = "";
}

$file <---- Puts out about 14 different lines
$fileContentArray = array();

for($i = 0; count($file) > $i; $i++){

            $var1 = "randomstuff1: " . $i;
            $var2 = "randomstuff2: " . $i;
            $var3 = "randomstuff3: " . $i;
            $temp = new Functions();
            $temp->$var1 = $var1;
            $temp->$var2 = $var2;
            $temp->$var3 = $var3;
            $fileContentArray[] = $temp;
            echo $fileContentArray[$i]->$var3; <--- Doesn't Give Errors
    }

    echo $fileContentArray[0]->$var3; <--- Gives Errors 
    echo $fileContentArray[1]->$var3; <--- Gives Errors
    echo $fileContentArray[13]->$var3; <--- Doesn't give error, final entry in array

【问题讨论】:

    标签: php


    【解决方案1】:

    除非您想要变量变量,否则不应在对象属性(变量)上使用“$”

    class Functions{
    
        public $var1 = "";
        public $var2 = "";
        public $var3 = "";
    }
    
    $file <---- Puts out about 14 different lines
    $fileContentArray = array();
    
    for($i = 0; count($file) > $i; $i++){
    
                $var1 = "randomstuff1: " . $i;
                $var2 = "randomstuff2: " . $i;
                $var3 = "randomstuff3: " . $i;
                $temp = new Functions();
                $temp->var1 = $var1;
                $temp->var2 = $var2;
                $temp->var3 = $var3;
                $fileContentArray[] = $temp;
                echo $fileContentArray[$i]->$var3; <--- Doesn't Give Errors
        }
    
        echo $fileContentArray[0]->var3; <--- Gives Errors 
        echo $fileContentArray[1]->var3; <--- Gives Errors
        echo $fileContentArray[13]->var3; <--- Doesn't give error, final entry in array
    

    编辑:请参阅此作为参考

    http://www.php.net//manual/en/language.variables.variable.php

    http://www.php.net//manual/en/sdo.sample.getset.php

    【讨论】:

      猜你喜欢
      • 2011-12-06
      • 2013-04-30
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 2019-05-08
      • 2019-09-19
      • 2016-05-08
      • 1970-01-01
      相关资源
      最近更新 更多