Is it possible to use php functions inside heredoc?

Is it possible to use functions within the heredoc template without breaking it? Somethig like this:

<<<HTML
   <div> showcaptcha(); </div>
HTML;

Specifically i wanna require another template in this one without using variables. Or is there another and more simple solution that is not using heredoc? Thx in advanced.

For example im using class named requires.

class requires {

public function __construct(){
  $this->MYSQL();
  $this->FUNC();
}

public function MAIN_MENU() {
  require_once ('main-menu.tpl');
}

}

Then what i do in index.php

require_once ('requires.php');
$req = new requires();

echo <<<HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>

//bla bla

</head>
<nav><ul class="fancynav">
{$req->HEAD_SCRIPTS()}
</ul></nav>
HTML;

main-menu.tpl

<li><a href="">Item</a></li>
<li><a href="">Item</a></li>
<li><a href="">Item</a></li>
<li><a href="">Item</a></li>
<li><a href="">Item</a></li>

And in result i have an empty field without php error

<nav><ul class="fancynav">



</ul></nav>

WTF?

Upvotes: 4

Views: 5479

Answers (3)

Xenos
Xenos

Reputation: 3507

Since you cannot directly call a function inside HEREDOC, you may put the function name in a variable, and use that variable inside the HEREDOC string:

    $showcaptcha= 'showcaptcha';
    echo
<<<HTML
    <br/> dawg {$showcaptcha()} dawg
HTML;

So you can leave the current already coded function:

    function showcaptcha()
    {
        return "Gotta captcha mall";
    }

You could also use:

    $showcaptcha = function()
    {
        return "Gotta captcha mall";
    }
    echo
<<<HTML
    <br/> dawg {$showcaptcha()} dawg
HTML;

If the function to call is defined at the same level as the echo (else, you'll have a global variable $showcaptcha).

If you have several functions, you can make a loop before the heredoc:

    function dawg()
    {
        return "I'm loyal";
    }
    function cat()
    {
        return "I'm cute";
    }
    function fish()
    {
        return "I'm small";
    }
    function elephant()
    {
        return "I'm big";
    }

    $functionsToCall = array('elephant', 'fish', 'cat', 'dawg');
    foreach ($functionsToCall as $functionToCall)
        $$functionToCall = $functionToCall;
    echo
<<<HTML
    <br/> Dawg: {$dawg()}
    <br/> Cat: {$cat()}
    <br/> Fish: {$fish()}
    <br/> Elephant: {$elephant()}
HTML;

That's way less ugly than using a global variable

Upvotes: 1

georg
georg

Reputation: 214959

Yes, you can use the "encapsed var" trick:

function hello() {
    global $result;
    $result = 'hi there!';
    return 'result';
}

echo <<<EOF
text ${hello()} text
EOF;

Technically, this works, but it's better to avoid hacks like this in production. A temporary variable will be much cleaner.

Upvotes: 7

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13283

No, it is not possible to use function inside heredoc strings.

Upvotes: -1

Related Questions