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

报告相同问题?

悬赏问题

  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥15 人在外地出差,速帮一点点