Getting a value of a dynamic class and dynamic property

117 views Asked by At

Is it possible to get the value of a instance variable that is a class and the value needed to get is just a string? I'm getting strings that are "$user->Prop" lets say, and I want to eval() this string to get the value, but it seems the eval function doesn't know about $user even though it is an instance variable.

$user->Prop = 3;
$a = "user->Prop";
$val = eval($$a); //how to get 3 with this string?

I know I can do

$prop = "prop";
$user->$prop;

and get 3, but in this case I'm trying to only pass in the variable I want to test and get the value in short.

3

There are 3 answers

1
dev-null-dweller On BEST ANSWER

eval does not return result of evaluated, if you want to store property value in $val, you have to include it in evaluated string:

$a = 'user->prop';
$eval = '$val = $'.$a.';';

eval($eval);
var_dump($val);
1
Rooster On

This won't work because you can't represent the -> dynamically.

$user->Prop = 3;
$a = "user->Prop";
$val = ${$a};

But you can do this:

$user->Prop = 3;
$a = "user";
$b = "Prop";
$val = ${$a}->$b;
0
Justin T. Watts On

Turns out if I have a string(11)"$user->Prop" and it is stored in $a what I need to do is:

$val = eval("return $a;");

need to read the docs more closely...good to write about it I guess though.