PHP:如何动态更改“if”条件顺序

时间:2011-05-14 14:11:55

标签: php dynamic if-statement

情况是这样的:有一个连续的循环,它会更新一些值。然后脚本检查某些条件。 (简化)代码:

<?php
set_time_limit(0);
// etc
while(1==1)
{
    $a = getFromDatabase('a'); // function to get value of A
    $b = getFromDatabase('b'); // function to get value of B
    $c = getFromDatabase('c'); // function to get value of C
    $d = getFromDatabase('d'); // function to get value of D

    if($a >= 12 && time() <= $b && ($d === false || $d <= time()))
    {
         include 'pages/'.$a.'.php';
    }
    if($b <= 3 && time() >= $d && ($c === false || $c <= time()))
    {
         include 'pages/'.$b.'.php';
    }
}

我的问题是:如何动态更改这些IF语句的顺序?

$order = array('b','a'); // first b then a

重要提示:if条件确实是动态的。所以没有真正的模式(上面的例子是简化的,所以不是完整的条件)

2 个答案:

答案 0 :(得分:2)

将它们放入函数中,然后只存储函数的名称并依次遍历每个函数。

function func1($a, $b, $c, $d)
{
  if (...)
  {
    return $a
  }
  return false;
}

function func2($a, $b, $c, $d)
 ...

$funcs = Array('func1', 'func2');

 ...

foreach($funcs as $func)
{
  if ($page = $func($a, $b, $c, $d))
  {
    include "pages/$page.php"
  }
}

答案 1 :(得分:1)

不确定这是否是您想要的,但您可以将if放入函数中:

<?php
set_time_limit(0);
function a($a,$b,$c,$d){
        if($a >= 12 && time() <= $b && ($d === false || $d <= time()))
        {
             include 'pages/'.$a.'.php';
        }
}
function b($a,$b,$c,$d){
        if($b <= 3 && time() >= $d && ($c === false || $c <= time()))
        {
             include 'pages/'.$b.'.php';
        }
}

// etc
while(1==1)
{
    $a = getFromDatabase('a'); // function to get value of A
    $b = getFromDatabase('b'); // function to get value of B
    $c = getFromDatabase('c'); // function to get value of C
    $d = getFromDatabase('d'); // function to get value of D
    $order = array('b','a'); // first b then a
    foreach( $order as $fun)
        call_user_func_array($fun, array($a,$b,$c,$d))
}