phpevaldynamic-classdynamic-properties

Getting a value of a dynamic class and dynamic property


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.


Solution

  • 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);