PHP变量给出“未定义属性”;错误


PHP Variable giving "Undefined property:" error

我创建了一个名为Functions的类,它存储了3个公共变量($var1, $var2, $var3)。我有一个for循环,它创建了这个类的一个对象,它更新了这个类的变量,然后把这个对象添加到一个数组中。然而,当我尝试访问数组时,我得到一个错误"未定义的属性:函数::$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

你不应该在对象属性(变量)上使用"$",除非你想要变量

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