doupian9798 2018-11-23 16:01 采纳率: 100%
浏览 87
已采纳

使用数字评估连续运算符

I'm struggling with a small piece of code that doesn't want to evaluate itself :

$t = 5;
$s = "<=";
$r = 6;

var_dump($t.$s.$r);

Here the var_dump return "5<=6" which make sense but I just want it to tell me if 5 is inferior or equal to 6 with a boolean.

I wanted to know if there was an other way to get this boolean beside using an eval() or a switch throught all the possible operator

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dousha2020 2018-11-23 16:16
    关注

    If you want a safe and flexible solution, this allows you to define a method which is executed depending on the operator matching the key in an array, it only works with two operands, but the last one in the examples # just multiplies the first value by 4 and returns the value...

    $operators = [ "<=" => function ($a, $b) { return $a <= $b;},
        "<" => function ($a, $b) { return $a < $b;},
        ">=" => function ($a, $b) { return $a >= $b;},
        ">" => function ($a, $b) { return $a > $b;},
        "#" => function ($a) { return $a * 4; }];
    
    $t = 5;
    $s = "<=";
    $r = 6;
    var_dump($operators[$s]($t,$r));
    
    $s = "<";
    var_dump($operators[$s]($t,$r));
    
    $s = ">=";
    var_dump($operators[$s]($t,$r));
    
    $s = ">";
    var_dump($operators[$s]($t,$r));
    
    $s = "#";
    var_dump($operators[$s]($t,$r));
    

    gives...

    /home/nigel/workspace2/Test/t1.php:14:
    bool(true)
    /home/nigel/workspace2/Test/t1.php:17:
    bool(true)
    /home/nigel/workspace2/Test/t1.php:20:
    bool(false)
    /home/nigel/workspace2/Test/t1.php:23:
    bool(false)
    /home/nigel/workspace2/Test/t1.php:26:
    int(20)
    

    It's a bit convoluted, but also extensible and safe.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法