irken Posted April 14, 2007 Share Posted April 14, 2007 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. Quote Link to comment Share on other sites More sharing options...
Barand Posted April 14, 2007 Share Posted April 14, 2007 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. Quote Link to comment Share on other sites More sharing options...
irken Posted April 14, 2007 Author Share Posted April 14, 2007 Ah, I should've noticed that. The array should be: ('testvar' => 'something elseeee') rather than ('testvar', 'something elseeee') Thanks, now I can finally get on with it : ). Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.