conditional statements inside php heredocs syntax?

getaway picture getaway · Oct 25, 2010 · Viewed 12.1k times · Source

i was wondering if you can have conditional statments inside a heredocs, this is my script but it deosnt parse out the $username properly?

php code:

function doSomething($username) {

if (isset($_SESSION['u_name'])){
$reply ='<a class ="reply" href="viewtopic.php?replyto=@$username.&status_id=$id&reply_name=$username"> reply </a>';

return <<<ENDOFRETURN

$reply

ENDOFRETURN;

the problem with this is the $username variable deosnt get rendered on the html. it remains $username :)) thanks

Answer

tfont picture tfont · Aug 11, 2015

Easy. Wrap everything in curly braces (obviously supported in Heredocs) and then use an anonymous function and return what is necessary for the logic :] you can even get advance with it and use expressions inside the the anonymous function variable within the heredocs.

Example:

// - ############# If statement + function to set #################


$result = function ($arg1 = false, $arg2 = false)
{
    return 'function works';
};

$if = function ($condition, $true, $false) { return $condition ? $true : $false; };


// - ############# Setting Variables (also using heredoc) #########


$set = <<<HTML
bal blah dasdas<br/>
sdadssa
HTML;

$empty = <<<HTML
data is empty
HTML;

$var = 'setting the variable';


// - ############## The Heredoc ###################################


echo <<<HTML
<div style="padding-left: 34px; padding-bottom: 18px;font-size: 52px; color: #B0C218;">
    {$if(isset($var), $set, $empty)}
    <br/><br/>
    {$result()}
</div>
HTML;