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. Link to comment https://forums.phpfreaks.com/topic/47028-solved-assigning-values-to-variables-within-a-class-from-a-foreach-loop/ 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. Link to comment https://forums.phpfreaks.com/topic/47028-solved-assigning-values-to-variables-within-a-class-from-a-foreach-loop/#findComment-229350 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 : ). Link to comment https://forums.phpfreaks.com/topic/47028-solved-assigning-values-to-variables-within-a-class-from-a-foreach-loop/#findComment-229351 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.