我可以在字符串中存储逻辑比较吗?

时间:2013-01-24 01:22:38

标签: php if-statement conditional modularity modularization

我正在尝试模块化一个冗长的if..else函数。

$condition = "$a < $b";
if($condition)
{
    $c++;
}

有没有办法将文字字符串翻译成逻辑表达式?

4 个答案:

答案 0 :(得分:7)

  

我正在尝试将冗长的if..else函数模块化。

您不需要将条件放在字符串中,只需存储布尔值truefalse

$condition = ($a < $b);
if($condition)
{
    $c++;
}
  

$ a和$ b的值可能会在$ condition的定义及其用法之间发生变化

一个解决方案是Closure(假设定义和用法发生在同一范围内):

$condition = function() use (&$a, &$b) {
    return $a < $b;
}
$a = 1;
$b = 2;
if ($condition()) {
    echo 'a is less than b';
}

但我不知道这是否对你有意义而不知道你想要完成什么。

答案 1 :(得分:2)

如果您知道足以确定结果的变量

,请使用lambda
$f = function ($a, $b) { return $a < $b; }

if ($f($x, $y)){}

答案 2 :(得分:1)

您可以使用eval执行此操作。但不确定为什么你不会立即评估这个条件。

答案 3 :(得分:-4)

<?php
     $a=0;
     $b=1;
    function resultofcondition()
    {
        global $a,$b;
        return $a<$b;
    }
    if(resultofcondition()){
        echo " You are dumb,";
    }else{
        echo " I am dumb,"; 
    }
    $a=1;
    $b=0;
    if(resultofcondition()){
        echo " You were correct.";
    }else{
        echo " in your face.";
    }
?>

确实感谢你发表评论,错过了GLOBAL参数,对于那些投票失败的人来说,该代码会输出什么? ¬_¬w / e玩得开心xD

相关问题