简体   繁体   中英

PHP Variable giving “Undefined property:” error

I have created a class called Functions which stores 3 public variables ($var1, $var2, $var3). I have a for loop that creates an object of that class, that updates the variables of the class and then add that object to an array. However, when I try and access the array, I get an error "Undefined property: Functions::$InsertTextHere".

The strange thing is, it doesn't play the error if I check the array at [$i], only if I check anywhere else in the array that was created in a previous iteration. For example, the echo within the for loop will not spark the error however the echos outside the for loop will.

I am sorry if this is hard to understand, please let me know if it is.

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

You shouldn't use "$" on the object properties (variable) unless you want variable variables

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

Edit: please see this as referrences

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM