简体   繁体   中英

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?

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.

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

不,不可能在heredoc字符串中使用函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM