PHP使用字符串作为运算符 [英] PHP use string as operator
本文介绍了PHP使用字符串作为运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ char。 $ char ==*。
我还有两个变量$ a和$ b,等于4和5
如何获取 $ a $ char $ b的结果,即4 * 5?
感谢:)
解决方案
您可以使用 eval()
按照@konforce的建议,但最安全的路由如下:
$ left =(int)$ a;
$ right =(int)$ b;
$ result = 0;
switch($ char){
case*:
$ result = $ left * $ right;
break;
case+;
$ result = $ left + $ right;
break;
// etc
}
Say I have a string, $char. $char == "*".
I also have two variables, $a and $b, which equal "4" and "5" respectively.
How do I get the result of $a $char $b, ie 4 * 5 ?
Thanks :)
解决方案
You can use eval()
as suggested by @konforce, however the safest route would be something like:
$left = (int)$a;
$right = (int)$b;
$result = 0;
switch($char){
case "*":
$result = $left * $right;
break;
case "+";
$result = $left + $right;
break;
// etc
}
这篇关于PHP使用字符串作为运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文