Accessing class variables with a for loop

I would like to access class variables using a loop for

, here is my simple class

class test{
    public $var1 = 1;
    public $var2 = 2;
    public $var3 = 3;
    public $var4 = 4;
}


$class = new test();

      

This is how I am trying to access variables using a loop

for($i = 1; $i <= 4; $i++){
    echo $class->var.$i;
}

      

and I get the error Notice: Undefined property: test::$var in C:\xampp\htdocs\test\index.php on line 12

Well this is not a very big error and I do get the value echoed, but I still don't understand why I am getting this error?

also if i do like this everything works fine:

echo $class->var1;

      

+3


source to share


5 answers


You don't actually get the echo value, you get the $i

echo.

echo $class->var.$i;

interpreted as echo ($class->var).($i);

. Since var

it is not a variable (hence an error), it becomes echo ''.$i;

, so you get the value $i

. It just so happens that var1

it matters 1. (Change $var1

to something else and you can see what I mean)

To fix the problem, you can do this:



for($i = 1; $i <= 4; $i++){
    $class->{'var'.$i}
}

      

The material inside is calculated first {}

, so the correct property is read.

+2


source


for($i = 1; $i <= 4; $i++){
    $var = 'var' . $i;
    echo $class->$var;
}

      

Or, as mentioned in the comments, this will work in newer PHP versions



for($i = 1; $i <= 4; $i++){
    $class->{'var' . $i}
}

      

+6


source


The code doesn't do what you think it does. This is only repetition 1-4 because of yours $i

in the for loop. If you want to change the vars in the class, your output will still be 1-4.

The property values ​​undefined are the key: it tries to access the property var

.

If you want to store repeating and / or related data, especially in your example, it is usually better to store it as an array:

class test{
    public $vars;

    public function __construct()
    {
        $this->vars = array(1, 2, 3, 4);
    }
}

$obj = new test();

foreach($obj->vars as $var)
{
    echo $var;
}

      

+2


source


The dot (.) Operator is echoed instead of calling a member into the $ class.

One of many solutions:

for($i = 1; $i <= 4; $i++){
     echo $class->{'var'.$i};
}

      

live example here

+2


source


This already works fine on the most recent versions of PHP, but try this:

for($i = 1; $i <= 4; $i++){
    $v = 'var'.$i;
    echo $class->$v;
}

      

0


source







All Articles