dongyi1159 2016-01-23 16:52
浏览 42
已采纳

交换两个函数执行顺序的简写

I'm looking for an abbreviated way to write the following logic in Php:

if condition do
   function b
   function a
else do
   function a
   function b

Or rather, a simple way to swap the order that functions a and b are executed.

This is what I've come up with so far:

!$swap && a(); // Where $swap is a boolean
b();
$swap && a();

A use case could be changing the rendering order of display output e.g. html.

  • 写回答

5条回答 默认 最新

  • duanjiushu5063 2016-01-24 01:14
    关注

    You can do this with a loop consisting of two iterations. With an if/else containing each function calls as statements within the loop. A flag determines which function to run. After one iteration the flag is toggled, so next time the other function runs:

    function a() {
        echo 'a';
    }
    
    function b() {
        echo 'b';
    }
    
    function c($flip = false) {
    
        for($i=0; $i<2; $i++) {
            if(! $flip) {
                a();
            } else {
                b();
            }
            $flip = ! $flip; // On next run the other statement will run
        }
    
    }
    
    c($flip = false);
    c($flip = true);
    
    // Outputs: abba
    

    Or using the ternary operator:

    function d($flip = false) {
    
        for($i=0; $i<2; $i++, $flip=!$flip) {
            !$flip ? a() : b();
        }
    
    }
    

    In a html view:

    <?php for($i=0; $i<2; $i++) { if(! $flip) { // Change the block display order if flip is true. ?>
    
        <h2>Block Foo</h2>
        <p>...</p> 
    
    <?php } else { ?>
    
        <h2>Block Bar</h2>
        <p>...</p>
    
    <?php } $flip = !$flip; } ?>
    

    The context being that I wrote a CMS module, and wanted a simple option for the end user to change the order of html, without overriding templates. I hope someone finds this useful.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号