I would like to access class variables with for loop, 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 try to access variables with a loop
for($i = 1; $i <= 4; $i++){
echo $class->var.$i;
}
and i get error which says
Notice: Undefined property: test::$var in C:\xampp\htdocs\test\index.php on line 12
Well it’s not really a big error and i actualy get the value echoed but i still don’t understand why do i get this error?
also if i do it this way everything works fine:
echo $class->var1;
You’re not actually getting the value echoed, you’re getting
$iechoed.echo $class->var.$i;is being interpreted asecho ($class->var).($i);. Sincevarisn’t a variable (hence the error), it becomesecho ''.$i;, so you get the value of$i. It just so happens thatvar1has the value 1. (Change$var1to something else, and you’ll see what I mean)To fix the issue, you can do this:
The stuff inside the
{}is calculated first, so the correct property is read.