开发者

Variable variables in OOP

开发者 https://www.devze.com 2023-01-13 02:32 出处:网络
I\'m having a little struggle on this one and would appreciate some help. In PHP variable variables can easily be defined like this

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开发者_JAVA技巧:

$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!


This works for me:

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

$a = 'myvar';
$myObject = new foo();
$myObject->$a .= 'flow';
echo $myObject->$a; // prints stackoverflow


This should work

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

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

精彩评论

暂无评论...
验证码 换一张
取 消