我是php的新手,我在函数中有3个参数
function cal($x,$y,$op){
$z=$x.$op.$y;
return $z;
}
echo cal(3,4,'/');
我也试试这个:
$z=$x$op$y;
我得到3/4
作为答案,但我想要0.75
答案 0 :(得分:0)
试试这个:
function cal($x,$y,$op){
$z=$x.$op.$y;
return calculate_string($z);
}
echo cal(3,4,'/');
function calculate_string( $mathString ) {
$mathString = trim($mathString); // trim white spaces
$mathString = ereg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString); // remove any non-numbers chars; exception for math operators
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}