Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional statements inside php heredocs syntax?

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

like image 782
getaway Avatar asked Oct 25 '10 05:10

getaway


2 Answers

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;
like image 187
tfont Avatar answered Sep 22 '22 22:09

tfont


Do you want to have conditional statements in heredoc or do you wonder why your code does not work? Because currently you have no conditional statement inside heredoc, but it is not possible anyway.

If you wonder why your code does not work:
This is not related to heredoc, it is because the entire $reply string is enclosed in single quotes, where variable parsing is not supported. Use string concatenation:

$reply ='<a class ="reply" href="viewtopic.php?replyto=@' . $username . '.&status_id=$id&reply_name=' . $username . '"> reply </a>'

I hope you are doing more with heredoc in your real code, otherwise return $reply would be easier ;) (and you are missing brackets).

like image 25
Felix Kling Avatar answered Sep 22 '22 22:09

Felix Kling