PHP: return value from function and echo it directly?

前端 未结 7 1559
遇见更好的自我
遇见更好的自我 2020-12-31 05:44

this might be a stupid question but …

php

function get_info() {
    $something = \"test\";
    return $something;
}
<
相关标签:
7条回答
  • 2020-12-31 06:18

    Why return when you can echo if you need to?

    function 
    get_info() {
        $something = "test";
        echo $something;
    }
    
    0 讨论(0)
  • 2020-12-31 06:26

    You could add it as a parameter so that you can echo or return depending on the situation. Set it to true or false depending on what you would use most.

    <?php
    function get_info($echo = true) {
    
        $something = "test";
    
        if ($echo) {
            echo $something;
        } else {
            return $something;
        }
    
    }
    
    ?>
    
    <?php get_info(); ?>
    <?php echo get_info(false); ?>
    
    0 讨论(0)
  • 2020-12-31 06:35

    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.

    0 讨论(0)
  • 2020-12-31 06:36

    Why not wrap it?

    function echo_get_info() {
      echo get_info();
    }
    

    and

    <div class="test"><?php echo_get_info(); ?></div>
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-31 06:41

    Have the function echo the value out itself.

    function get_info() {
        $something = "test";
        echo $something;
        return $something;
    }
    
    0 讨论(0)
提交回复
热议问题