eval - process embedded variable within a string using PHP -
how process variable embedded within string? string came database, here example:
1: $b='world!'; 2: $a='hello $b'; #note, used single quote purposely emulate string database (i know different of using ' or "). 3: eval($c=$a.";"); #i know not work, trying $c="hello $b"; #with line 3 php code, trying outcome of $c='hello world!';
if want eval line of code $c='hello world';
should have string when echo
ed that: $c="hello $b";
.
so - start, $c
variable should inside string (and not variable);
'$c'
next - =
sign should inside string (and not part of php code, otherwise preprocessor try assign value on right variable on left.
how one:
$new_str = '$c=' . $a . ';'; echo $new_str;
now can see value inside $new_str
actually:
$c=hello $b;
which not valid php code (because don't have hello in php. want have hello $b part inside double-quote:
$new_str = '$c="' . $a . '";';
and can eval this.
so final code should like:
$b='world!'; $a='hello $b'; eval('$c="' . $a . '";'); echo $c; // hello world!
Comments
Post a Comment