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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.