3

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!

3
  • 1
    "variable variables can easily be defined" Please refrain from using them (in OOP or otherwise). You can thank me later. Commented Aug 27, 2010 at 6:57
  • I know what you mean and actually use them very rarely. Right now I'm having a situation where it makes sense. Commented Aug 27, 2010 at 7:11
  • 1
    If you are using variable variables, then you do not understand OOP Commented Aug 27, 2010 at 7:18

2 Answers 2

2

This works for me:

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

$a = 'myvar';
$myObject = new foo();
$myObject->$a .= 'flow';
echo $myObject->$a; // prints stackoverflow
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I was actually doing right, the error was somewhere else where I forgot to access $myObject->$a but tried to get $a directly.
2

This should work

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.