算术运算符(+ - / *)在PHP中有什么类型?我有这种情况:
$argX= "1";
$argY = "2";
$operator = "+";
我想在变量中使用运算符添加两个参数。像这样的Smth:
$result = $argX $operator $argY;
我知道参数是字符串,所以我先将它们转换为数字。
$argX = $argX+0;
$argY = $argY+0;
但是我应该将$operator
转换为使用值$operator
变量添加参数?怎么可能?
答案 0 :(得分:6)
不,这是不可能的。您不能在PHP中为运算符使用表达式。运营商是运营商,他们没有类型。你必须做这样的事情:
switch ($operator) {
case '+' : $result = $argX + $argY; break;
case '-' : $result = $argX - $argY; break;
...
}
你可以 eval
它,但我不建议这样做。
答案 1 :(得分:3)
你做不到,但是你可以做到
if($operator == '+')
{
//math
}
答案 2 :(得分:1)
类似的东西:
// allowed operators
$allowed = array('+','-','/','*','%');
// check to see that operator is allowed and that the arguments are numeric
// so users can't inject cheeky stuff
if(in_array($operator, $allowed) && is_numeric($argX) && is_numeric($argY)){
eval('<?php $result = '.$argX.' '.$operator.' '.$argY.'; ?>');
}
答案 3 :(得分:0)
名为operator的函数也不会起作用吗?
function operator($X, $Y) {
$Z = $X + $Y;
return $Z
}
$Z = operator($X,$Y);