PHP:从函数返回值并直接回显它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11020575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:35:06  来源:igfitidea点击:

PHP: return value from function and echo it directly?

phpfunctionecho

提问by matt

this might be a stupid question but …

这可能是一个愚蠢的问题,但是……

php

php

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

html

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!

对此有何想法?先感谢您!

回答by Scott Saunders

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;
}

回答by Ruslan Osipov

Why return when you can echo if you need to?

如果需要,为什么可以回声时返回?

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

回答by Eugen Rieck

Why not wrap it?

为什么不包起来?

function echo_get_info() {
  echo get_info();
}

and

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

回答by ewein

Have the function echo the value out itself.

让函数自己回显值。

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

回答by Rem.co

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

访问echo的手册页就会得到答案,这确实是之前的答案提到的:快捷语法

Be very careful though, if short_open_tagis 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).

但是要非常小心,如果short_open_tag在 中禁用php.ini,则快捷方式 echo 将不起作用,并且您的代码将在 HTML 中输出。(例如,当您将代码移动到具有不同配置的不同服务器时)。

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

为了降低代码的可移植性,我建议不要使用它。

回答by Madara's Ghost

Sure,

当然,

Either print it directly in the function:

要么直接在函数中打印它:

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

Or use the PHP's shorthand for echoing:

或者使用 PHP 的速记来回显:

<?= 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.

虽然我建议你保留回声。返回函数可读性更强,更容易维护,不推荐使用简写。