krystian2160
krystian2160

Reputation: 143

Eval in replacing and resolving variables inside a PHP string

$html = '<html><body>$DATA</body></html>';

$DATA = "<h1>Hi</h1>";

eval("\$html = \"$html\";");
echo $html;

The above piece of code will resolve the variable of $DATA properly. While

$html = '<html><body>$DATA</body></html>';

$DATA = "<h1>Hi</h1>";

$html = "$html";

echo $html;

This piece of code will not. Why? What is the difference between these two?

Isn't the eval("\$html = \"$html\";"); equal to just $html = "$html"; ?

Why first one works while the other one doesn't?


As in my above examples; $DATA is and must be defined after the $html. That's the case :). In other case I wouldn't even have a question and bother.

But it's... why first one works while second one doesn't. And how to make the second one works? But primarly why it doesn't in fact work.

Upvotes: 0

Views: 251

Answers (1)

Syscall
Syscall

Reputation: 19764

In the first case $DATA inside $html is evaluated during the eval(), and at this point $DATA is defined (because, defined before eval()).

In the second case, $DATA is interpolated on this line $html = '<html><body>$DATA</body></html>'; and at this point $DATA is undefined.

$DATA = "<h1>Hi</h1>";
$html = "<html><body>$DATA</body></html>";

The code above works because $DATA is defined before the evaluation.

As @NigelRen pointed out, in the second case, the string use single quotes and variable won't be interpolated inside "single-quoted" strings.

Upvotes: 1

Related Questions