2

I have an simple question,

How to insert PHP code in PHP variable?

Example :

echo $value = "
bla
bla
<?php $q = "SELECT * FROM BLA BLA"; ?>
";
3
  • 6
    There is a 100% chance of a solution for your application which does not require putting PHP code into a variable the way you demonstrated. Commented Mar 24, 2014 at 10:50
  • 1
    echo $value = ' bla bla <?php $q = "SELECT * FROM BLA BLA"; ?> '; like @AwladLiton mentions Commented Mar 24, 2014 at 10:59
  • 1
    It's unclear what you expect that code to do... and it smells like an XY problem: meta.stackexchange.com/questions/66377/what-is-the-xy-problem - my advice: anyone who posts an answer without figuring out what the OP really wants should be downvoted. Commented Mar 24, 2014 at 11:05

1 Answer 1

4

You can do it using eval()

$test = <<<END
<p> <?php 
echo time(); 
?> </p>
END;
    
   
ob_start();
eval("?>$test");
$result = ob_get_clean();

Or an other example from w3s:

<?php
$string = "beautiful";
$time = "winter";

$str = 'This is a $string $time morning!';
echo $str. "<br>";

eval("\$str = \"$str\";");
echo $str;
?>

will print

This is a $string $time morning!

This is a beautiful winter morning!

Source

But be very carefull when you use it, from the php page:

Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

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

3 Comments

Please... just DON'T.
What do you mean? Don't use it?
The link to the manual could give you an idea about eval(). Manual on eval()

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.