将逻辑运算符的条件变为变量

时间:2013-11-04 11:33:37

标签: php if-statement logical-operators

我想用逻辑运算符(&&或||)将条件设置为一个带连接的变量,然后运行if($ var)...

<?php 
$ar = array(
'index1' => array('bedrooms'=> '1','suburb' => 'one'),
'index2' => array('bedrooms'=>'2', 'suburb'=>'two')
);
$userValBed = '1';
$userSuburb = 'one';

$c = '';
$c .= '($value["'.'bedrooms'.'"] == "'.$userValBed.'") && ';
$c .= '($value["'.'suburb'.'"] == "'.$userSuburb.'")';

foreach($ar as $key => $value){
   if($c): // here occurs problem, please fix this.
   // if($value["bedrooms"] == "1" && $value["suburb"] == "one"): // comment this line, and uncommet above 'if'.
   echo "<br>";
   echo "this condtions matches to ";
   echo $key . ' key '. '<br>';
endif;
}
?>

2 个答案:

答案 0 :(得分:0)

您可以使用的是Command pattern。命令模式试图将类中的功能包装起来。这样做的好处是,您可以通过在配置中指定所需内容来在运行时交换功能。 Here是一个更深入的解释。

class Command {
    function doSomething($v1, $v2);
}

然后您创建该类的子类:

class CommandAdd extends Command
{
    function doSomething($v1, $v2)
    {
         return $v1 === $v2;
    }
}

您可以根据需要使用doSomething制作任意数量的课程。然后,您所要做的就是定义您的功能:

$command = new CommandAdd();

if($command->doSomething()) { 
   // Code here 
}

您可以在外部文件或类似内容中指定Command的类型。

答案 1 :(得分:0)

将代码放入变量中并不是一个好的设计。它可能有用,但它很丑陋且难以理解。

相反,您可以使用内部 foreach 来检查用户的参数是否与项目的参数匹配。

无论如何,将数据存储在某种数据库(例如SQL数据库)中会更好,因此问题将变为:如何根据用户的参数创建SQL查询。

相关问题