PHP: return value from function and echo directly?

This may be a stupid question, but ...

Php

function get_info() {
    $something = "test";
    return $something;
}

HTML

<div class="test"><?php echo get_info(); ?></div>

Is there a way to make the function automatically "echo" or "print" the returned statement? How do I want to do this ...

<div class="test"><?php get_info(); ?></div>

... without an β€œecho” in it?

Any ideas on this? Thank you in advance!

+5
source share
6 answers

You can use special tags:

<?= get_info(); ?>

Or, of course, you can force your function to echo a value:

function get_info() {
    $something = "test";
    echo $something;
}
+17
source

Why come back when you can echo if you need to?

function 
get_info() {
    $something = "test";
    echo $something;
}
+6
source

echo , : .

, short_open_tag php.ini, , HTML. (, , ).

For reduced code portability, I would suggest using it.

+2
source

Why not wrap it?

function echo_get_info() {
  echo get_info();
}

and

<div class="test"><?php echo_get_info(); ?></div>
+1
source

Of course,

Or type it directly in a function:

function get_info() {
    $something = "test";
    echo $something;
}

Or use a shorthand PHP expression for echo:

<?= get_info(); ?>

Although I recommend you keep the echo. It is more readable and easier to support return functions, and abbreviations are not recommended for use.

+1
source

The function echoes the meaning of itself.

function get_info() {
    $something = "test";
    echo $something;
    return $something;
}
+1
source

All Articles