How to rewrite php echo with <<

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

I am wondering how to rewrite this code to work with qq:

  $containerRight = <<<qq
    <div class="container_right">
        {echoLikeBox()}

        <div class="join_us"><a href="#"><img src="images/join_us.png" width="304" height="44" alt=""></a></div>

        <div class="box2"><a href="#"><img src="images/twitter_big.gif" width="304" height="292" alt=""></a></div>

        <div class="box3"><a href="#"><img src="images/facebook.jpg" width="304" height="257" alt=""></a></div>

        <div class="box4"><a href="#"><img src="images/google_ads.gif" width="304" height="164" alt=""></a></div>
    <!-- container_right end --></div>;
    qq;
    echo $containerRight;

The problem is that I don’t know how to echo function inside the <<<. The code for the echoLikBox() is this:

function echoLikeBox()
{
    $likeBox = <<<qq
    <div class="box1">
            <div class="box1_lft"><a href="#"><img src="images/tweet.jpg" width="108" height="20" alt=""></a></div>
            <div class="box1_rht"><a href="#"><img src="images/like.jpg" width="82" height="20" alt=""></a></div>
            <div class="clear"></div>
    </div><!-- box1 end -->
    qq;
    echo $likeBox;
}

edit: found the solution here: Calling PHP functions within HEREDOC strings

 

The answer, by user Gavin Anderegg, was:

You may want to change the “echoLikeBox()” function to, instead of echoing its contents, store them as a string. You can’t make a call to a function inside of heredoc strings, but you can output variables. So, for example, you could have:

function echoLikeBox()
{
    $likeBox = <<<qq
    <div class="box1">
            <div class="box1_lft"><a href="#"><img src="images/tweet.jpg" width="108" height="20" alt=""></a></div>
            <div class="box1_rht"><a href="#"><img src="images/like.jpg" width="82" height="20" alt=""></a></div>
            <div class="clear"></div>
    </div><!-- box1 end -->
qq;
    return $likeBox;
}

and then just

$likeBox = echoLikeBox();

$containerRight = <<<qq
    <div class="container_right">
        $likeBox

        ...

inside of the main body.

Written by Nikola Brežnjak