运算符(操作数?)作为参数 [英] Operators (operands?) as Parameters

查看:372
本文介绍了运算符(操作数?)作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



基本上..

  $ op = $ _POST ['operator']; 
$ x = 5;
$ y = 2;
$ result = $ x / * $ op而不是'+'/' - '/'*'/'/'/'%'* / $ y;

这是可能的还是将我作为一个字符串发送给操作符并且复制每个操作符类型的代码?

解决方案



  $ x = 5; 
$ y = 2;
$ b switch($ _ POST ['operator']){
case'+':
$ result = $ x + $ y;
休息;
case' - ':
$ result = $ x - $ y;
休息;
case'*':
$ result = $ x * $ y;
休息;
case'/':
$ result = $ x / $ y;
休息;
case'%':
$ result = $ x%$ y;
休息;
默认值:
$ result ='不支持的操作符';
}

这些行是。


I am trying to avoid duplicating my code by checking the variable if it is a certain operator.

Basically..

$op = $_POST['operator'];
$x = 5;
$y = 2;
$result = $x /* $op instead of '+'/'-'/'*'/'/'/'%' */ $y;

Is this possible or will I have to send the operator as a String and duplicate the code per operator type?

解决方案

It's a lot safer to do something like this:

$x = 5;
$y = 2;

switch($_POST['operator']){
    case '+':
        $result = $x + $y;
        break;
    case '-':
        $result = $x - $y;
        break;
    case '*':
        $result = $x*$y;
        break;
    case '/':
        $result = $x/$y;
        break;
    case '%':
        $result = $x % $y;
        break;
     default:
        $result = 'Operator not supported';
}

Something along those lines.

这篇关于运算符(操作数?)作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆