PHP中的算术运算符(+-/*)有什么类型?我有这样的情况:
$argX= "1";
$argY = "2";
$operator = "+";
我想用变量中的运算符把两个参数加起来。Smth是这样的:
$result = $argX $operator $argY;
我知道自变量是字符串,所以我先把它们转换成数字。
$argX = $argX+0;
$argY = $argY+0;
但是,在什么情况下,我应该转换$operator
以使用$operator
变量的值添加参数?这怎么可能?
不,这是不可能的。在PHP中,不能将表达式用于运算符。运算符是运算符,它们没有类型。你必须这样做:
switch ($operator) {
case '+' : $result = $argX + $argY; break;
case '-' : $result = $argX - $argY; break;
...
}
您可以eval
,但我不建议这样做。
你不能那样做,但你可以做
if($operator == '+')
{
//math
}
类似于:
// 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.'; ?>');
}
一个名为运算符的函数不也能工作吗?
function operator($X, $Y) {
$Z = $X + $Y;
return $Z
}
$Z = operator($X,$Y);