tags:

views:

79

answers:

2

Hi everyone I'm having a little struggle on this one and would appreciate some help.

In PHP variable variables can easily be defined like this

$a = "myVar";
$$a = "some Text";
print $myVar; //you get "some Text"

Now, how do I do that in a OOP enviroment? I tried this:

$a = "myVar";
$myObject->$a = "some Text"; //I must be doing something wrong here
print $myObject->myVar; //because this is not working as expected

I also tried $myObject->{$a} = "some Text" but it's not working either. So I must be very mistaken somewhere.

Thanks for any help!

+2  A: 

This works for me:

class foo {
    var $myvar = 'stackover';
}

$a = 'myvar';
$myObject = new foo();
$myObject->$a .= 'flow';
echo $myObject->$a; // prints stackoverflow
codaddict
Thanks! I was actually doing right, the error was somewhere else where I forgot to access `$myObject->$a` but tried to get `$a` directly.
sprain
+3  A: 

This should work

class foo {
    var $myvar = 'stackover';
}

$a = 'myvar';
$myObject = new foo();
$myObject->$a = 'some text';
echo $myObject->myvar;
Maulik Vora