phpconditional-statementsheredoc

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


Solution

  • 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).