【问题标题】:how to use operators as variables如何将运算符用作变量
【发布时间】:2016-04-06 21:25:36
【问题描述】:

我有一个变量 $operator,它的值为“+”或“-”。我也有两个数字作为变量 $no1,$no2。如何在不使用 if 语句的情况下添加或减去这些变量:

例如如果 $no1 = 7 且 $no2 = 14 且 $operator = +;我想要

$answer = $no1 $operator $no2

成为 7 + 14;或者本质上 $answer 的值为 21。这是如何完成的?

【问题讨论】:

  • eval($no1.$operator.$no2); 呢?
  • 解析错误:语法错误,/ajax-operator.php(7) 中出现意外的 '14' (T_LNUMBER):第 1 行的 eval() 代码
  • 使用这个:eval('echo '.$no1.$operator.$no2.';');
  • 您为什么不尝试编写 $operator($no1, $no2) 并将您的运算符定义为匿名函数,而不是 $no1 $operator $no2?

标签: php variables operators


【解决方案1】:

解决这个问题的一种方法是编写这样的函数:

function calculate($varOne, $operator, $varTwo) {
    switch($operator) {
        case '+':
            $result = $varOne + $varTwo;
            break;
        case '-':
            $result = $varOne - $varTwo;
            break;
        default:
            $result = 0;
            break;
    }
    return $result;
}

这里可以根据 $op 变量的值在 switch 语句中添加不同的计算。例如,您可以添加乘法或除法。

然后你可以像这样使用函数:

$result = calculate(7, '+', 14);
echo($result);

会产生:

21

$result 也持有 21。

当然,您可以在 $varOne 和 $varTwo 变量中添加诸如检查整数或浮点数之类的内容,但我会让您根据需要自行扩展。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 2021-04-21
    • 2017-01-15
    相关资源
    最近更新 更多