Functions in HEREDOC PHP

Asked

Viewed 34 times

0

I’ve been trying for a while but I can’t get the expected result, follow the example:

<?php
$titulo = "Título";
$foo = "foo";
function foo(){
    $i = 1;
    while($i <= 10){
        echo $i++;
    }
}
echo <<<EOT
<h1>{$titulo}</h1>
<p>Um texto qualquer</p>
<p>Chamada da função foo() {$foo()}</p>
EOT;
?>

Well in the example above, I have the function foo() with the return of a loop, so far so good, but when I call the function in HEREDOC, the result returns above the string, it does not return where the function was called, it returns at the beginning of the string, there is a way for me to solve this problem with HEREDOC?

1 answer

2


The echo does not work as return, when a string is being processed first all values and functions are processed, so foo() will be executed before the string generated in <<<EOT EOT; exist.

I mean, the moment that it runs {$foo()} the echo with HEREDOC still "does not exist", because it is processed all before to form the string or any value.

The same goes for arithmetic operations, such as:

echo foo() * bar() - baz();

The calculation is done and only then returned to echo, to solve you should use Return, so:

<?php
$titulo = "Título";
$foo = "foo";

function foo(){
    $output = '';

    $i = 1;
    while($i <= 10){
        $output .= $i++;
    }

    return $output;
}
echo <<<EOT
<h1>{$titulo}</h1>
<p>Um texto qualquer</p>
<p>Chamada da função foo() {$foo()}</p>
EOT;

Take the test online: https://repl.it/@inphinit/outpur-while-for-in-Return#main.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.