0
$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.

1 Answer 1

1

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.

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

3 Comments

But it's not what my question meant, mmmmm, $DATA is and must be defined after the $html
But isn't the eval("\$html = \"$html\";"); equal to $html = "$html"; ?
@krystian2160 No. This is not equal. In the case of eval, $html is evaluated, but in $html = "$html";, the $html is not evaluated and is equal to $html=$html; so, nothing changed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.