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 $i
echoed.
echo $class->var.$i;
is being interpreted as echo ($class->var).($i);
. Since var
isn't a variable (hence the error), it becomes echo ''.$i;
, so you get the value of $i
. It just so happens that var1
has the value 1. (Change $var1
to something else, and you'll see what I mean)
To fix the issue, you can do this:
for($i = 1; $i <= 4; $i++){
$class->{'var'.$i}
}
The stuff inside the {}
is calculated first, so the correct property is read.
for($i = 1; $i <= 4; $i++){
$var = 'var' . $i;
echo $class->$var;
}
Or, as mentioned in the comments, this will work in newer versions of PHP
for($i = 1; $i <= 4; $i++){
$class->{'var' . $i}
}
The code isn't doing what you think. It's only echoing 1-4 because of your $i
in the for loop. If you were to change the vars in the class, your output will still be 1-4.
The undefined property notices is the clue: it is trying to access the property var
.
If you want to store data that is repetitive and/or associated, especially like in your example, it is usually more suitable to store 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;
}
The dot (.) operator is getting used by the echo rather than the member call to $class.
One of many solutions:
for($i = 1; $i <= 4; $i++){
echo $class->{'var'.$i};
}
This already works fine on very recent PHP versions, but try this:
for($i = 1; $i <= 4; $i++){
$v = 'var'.$i;
echo $class->$v;
}