PHP: How to change "if"-condition order dynamically
The situation is like this: there is a continuous loop, that updates some values. Then the script checks certain conditions. The (simplified) code:
<?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'开发者_JAVA百科;
}
}
My question is: how can I change the order of these IF-statements dynamically?
Like
$order = array('b','a'); // first b then a
Important: the if conditions are really dynamic. So there is no real pattern (the example above is simplified, so not the full conditions)
Put them in functions, then just store the name of the functions and go through each in turn.
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"
}
}
Not sure if that's what you want, but you can put if
in functions:
<?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))
}
精彩评论