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条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大