我创建了一个名为Functions的类,它存储了3个公共变量($ var1,$ var2,$ var3)。我有一个for循环,它创建该类的对象,更新类的变量,然后将该对象添加到数组。但是,当我尝试访问数组时,我收到错误" Undefined属性:Functions :: $ InsertTextHere"。
奇怪的是,如果我在[$ i]检查数组,它不会播放错误,只有当我检查在前一次迭代中创建的数组中的任何其他地方时。例如,for循环中的回声不会引发错误,但for循环外的回声将会发生。
如果这很难理解,我很抱歉,如果有,请告诉我。
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
答案 0 :(得分:2)
你不应该使用&#34; $&#34;除非你想要变量
,否则在对象属性(变量)上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