duanduan1993 2013-03-08 18:35
浏览 19
已采纳

在php中回显函数是不好的做法吗?

Is it bad practice to echo out a bunch of HTML using a function in php and having it something like this:

function my_function() {
global $post;
$custom_fields = get_post_custom();
$some_field = $custom_fields ['some_field'][0];
?>

<div class="something <?php if ($some_field) { echo $special-clas;} ?>">
<div class="something-else">
/* bunch more of html code */
</div>
</div>
}

And then in the page where you want to use that to echo it?

<html>
<body>
.....
....

<?php echo my_function(); ?>

....

I'm unsure how "accepted" it is to echo out functions?

  • 写回答

6条回答 默认 最新

  • duanjing9339 2013-03-08 18:38
    关注

    Consider two functions:

    function does_return() {
       return 'foo';
    }
    
    function does_echo() {
       echo 'bar';
    }
    
    does_return();      // nothing displayed
    echo does_return(); // 'foo' displayed
    
    does_echo();        // 'bar' displayed
    echo does_echo();   // 'bar' displayed
    

    In both cases, output CAN be performed, but how it happens differs. Since does_return() does not itself have ANY code to perform output within its definition, output is up to the calling code, e.g. the echo you perform.

    With does_echo(), it doesn't matter how you call the function (with or without echo), since the function does the output itself. you'll get bar regardless.

    Now consider this:

    function this_is_fun();
        echo 'foo';
        return 'bar';
    }
    
    this_is_fun();       // outputs 'foo'
    echo this_is_fun();  // outputs 'foobar';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)