PHP: return value from function and echo it directly?

我的未来我决定 提交于 2020-01-10 14:09:10

问题


this might 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? Like I wanna do this … 

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

… without the "echo" in it?

Any ideas on that? Thank you in advance!


回答1:


You can use the special tags:

<?= get_info(); ?>

Or, of course, you can have your function echo the value:

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



回答2:


Why return when you can echo if you need to?

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



回答3:


Why not wrap it?

function echo_get_info() {
  echo get_info();
}

and

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



回答4:


Have the function echo the value out itself.

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



回答5:


One visit to echo's Manual page would have yielded you the answer, which is indeed what the previous answers mention: the shortcut syntax.

Be very careful though, if short_open_tag is disabled in php.ini, shortcutting echo's won't work, and your code will be output in the HTML. (e.g. when you move your code to a different server which has a different configuration).

For the reduced portability of your code I'd advise against using it.




回答6:


Sure,

Either print it directly in the function:

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

Or use the PHP's shorthand for echoing:

<?= get_info(); ?>

Though I recommend you keep the echo. It's more readable and easier to maintain returning functions, and the shorthands are not recommended for use.



来源:https://stackoverflow.com/questions/11020575/php-return-value-from-function-and-echo-it-directly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!