0

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.

Justin T. Watts
  • 547
  • 1
  • 4
  • 16
  • what does your class look like ? I think what you are trying to do should be simpler than this. – Maximus2012 Jul 17 '13 at 20:19
  • it would be far too much code to show, I did summarize what is happening in the code snip above. – Justin T. Watts Jul 17 '13 at 20:20
  • so I am assuming $user is an object of the user class. Something like $user = new User(). if Prop is declared as public in the user class then you should be able to get the value by doing something like: var_dump($user->Prop) – Maximus2012 Jul 17 '13 at 20:22
  • yes, but I only have a value of string(11)"$user->Prop" and want to eval to 3 in this case. – Justin T. Watts Jul 17 '13 at 20:25
  • ah, it turns out the eval function will return a value, but I must use return so in this case if I'm receiving "$user->Prop" I have to do $a = "/$user->Prop"; $val = eval("return $a;"); – Justin T. Watts Jul 17 '13 at 20:33

3 Answers3

3

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);
dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85
2

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;
Rooster
  • 9,954
  • 8
  • 44
  • 71
  • @tlenss ahhh. nice catch. Started up my Wamp and double checked. Edited my answer to correct your find. – Rooster Jul 17 '13 at 20:39
0

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.

Justin T. Watts
  • 547
  • 1
  • 4
  • 16