0

I've got a problem to share with you all. The thing is, I would like to extract the value of a complex object having its name stored in a string variable.

As you may know, you can do the following:

$foo = 'Hello World';

$var = 'foo';

echo var_dump($$var); // Output: string(11) "Hello World"

The problem comes when you try to do:

$data = new stdClass();

$data->param["foo"]["bar"] = 'Hello World';

$var = 'data->param["foo"]["bar"]';

echo var_dump($$var); // Output: NULL    

I can imagine why the parser can't do this. The only workaround that I can think of is to split $var into smaller chunks ('->', '[', ']', ...) and evaluate it step by step.

Does anyone know a more elegant solution?

Thanks a lot

2
  • i don't think its possible to use elements like -> or [ in that manner ... Commented Dec 23, 2010 at 12:03
  • "Variable variables" just have a variable variable name. They are not variable expressions. And sorry, there is no nicer workaround. But can you elaborate on your use case anyway? Commented Dec 23, 2010 at 12:04

2 Answers 2

1

Well, data->param["foo"]["bar"] is not a variable name, that's why you can't use it in $$var.

You are better off using eval() in this case, something like this

$var = 'return $data->param["foo"]["bar"];';
var_dump(eval($var));

And yeah, you don't need to echo var_dump, just var_dump

Sign up to request clarification or add additional context in comments.

Comments

0

Finally I could solve it by doing the following:

<?php

$data = new stdClass();

$data->param["foo"]["bar"] = 'Hello World';

$var = 'data->param["foo"]["bar"]';

$value = eval('return $'.$var.';');

var_dump($value);

4 Comments

It seems that your answer is generally the same as the answer by German Rumm. If you don't mind, please accept that answer by clicking the tick next to the post. Also, you don't really need the return in the eval string.
well i generally never advice using eval @Delan Azabani has a Point
That's true, Hannes, eval has a lot of small problems that can become big problems, as well as being inefficient, and should be avoided where there's a better alternative. I only know basic PHP so I don't really have an answer to contribute.
@Delan Azabani, it doesn't seem to work without return (var_dump() shows NULL), that's why I added it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.