yii2 - Accessing PHP variable inside a string stored in variable
Solution:
The variable in string only works when the string is evaluated by PHP processor. So it's only usable in strings in your source code. The string is not evaluated when it comes from other sources like DB or result of expression.
There are two options how you can solve your problem.
1) Use str_replace to replace variable inside your string
$stringFromDb = '<p>Some text with {$variable}</p>';
$text = str_replace('{$variable}', $variable, $stringFromDb);
echo $text;
This way is better because you can control in your source code what variables can be accessed. Also the string itself is not processed as code.
2) use eval()
to evaluate the string (not safe)
Because your string can contain some other text you need to modify it before evaluating it.
$variable = 'test';
$stringFromDb = '<h1>{$variable}</h1>';
$string = '$text = "' . $stringFromDb . '";';
eval($string);
echo $text;
You can only use this approach if you are sure the string from DB cannot contain any malicious code. Because an attacker can use this to run any php code.
Answer
Solution:
You have two options that I see.
Use just the text name of the variable and use a variable variable:
$str = 'foo';
$str2 = 'str';
echo $$str2;
//or
echo ${$str2};
//or
echo ${"$str2"};
Or evaluate the string inside the variable as a variable:
$str = 'foo';
$str2 = '$str';
eval("echo $str2;");
All output foo
.