Jump to content

[SOLVED] Assigning values to variables within a class, from a foreach loop


irken

Recommended Posts

Hello.

 

I was attemping to make an array of configuration variables for Smarty when I ran into this little problem. Here's some example code first of all:

 

<?php

class Testclass {
  var $testvar = 'something';
}

$test = new Testclass;
echo "before foreach: $test->testvar\n"; # echos 'something'

$arr = array('testvar', 'something elseeeee');

foreach ($arr as $key => $value) {
  $test->$key = $value; # set $test->[variable] to $value
}

echo "after foreach: $test->testvar\n"; #echos 'something'

 

Problem. This outputs "something" in both places, while I expected it to echo "something elseeee" after the foreach is done.

 

Setting $test->testvar manually and outputting it workes fine, but breaks in the foreach. To me this seems weird, but might just be how PHP workes. If that's the case, how do I work around this?

 

Thanks for reading.

foreach ($arr as $key => $value) {

  $test->$key = $value; # set $test->[variable] to $value

}

 

In the above loop, the $key var holds 0 then 1, so you are trying to set $test->0 to a value.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.