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 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)