Using a variable as an operator

后端 未结 11 1422
滥情空心
滥情空心 2020-12-06 09:31

So I have something like the following:

$a = 3;
$b = 4;
$c = 5;
$d = 6;

and I run a comparison like

if($a>$b || $c>$d         


        
相关标签:
11条回答
  • 2020-12-06 09:48

    No, it is not possible.

    0 讨论(0)
  • 2020-12-06 09:53

    nope. there is no way to do this in php.

    0 讨论(0)
  • 2020-12-06 09:58

    For future searchers, here's a function I came up with when I had a requirement to add some vague and undefined "additional criteria" for narrowing down a list of products.

    /**
     * Criteria checker
     *
     * @param string $value1 - the value to be compared
     * @param string $operator - the operator
     * @param string $value2 - the value to test against
     * @return boolean - criteria met/not met
     */
    protected function criteriaMet($value1, $operator, $value2)
    {
        switch ($operator) {
            case '<':
                return $value1 < $value2;
                break;
            case '<=':
                return $value1 <= $value2;
                break;
            case '>':
                return $value1 > $value2;
                break;
            case '>=':
                return $value1 >= $value2;
                break;
            case '==':
                return $value1 == $value2;
                break;
            case '!=':
                return $value1 != $value2;
                break;
            default:
                return false;
        }
        return false;
    }
    

    (edit) Here's how I used it:

    // Decode the criteria
    $criteria = json_decode($addl_criteria);
    
    // Check input against criteria
    foreach ($criteria as $item) {
        // Criteria fails
        if (!criteriaMet($input[$item->key)], $item->operator, $item->value)) {
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 09:58

    Please use this code for change the string operator to convert in actual format

     <?php
    
      $a = 3;
      $b = 4;
      $c = 5;
      $d = 6;
      $e='&&';
      $lt='<';
      $gt='>';
    
      if(eval('return '.$a.$lt.$b.$e.$c.$gt.$d.';')){
        echo "yes";
      }else{
        echo "No";
      }
    
    0 讨论(0)
  • 2020-12-06 09:58

    You could use eval, but that you could easily end up exposing your site to all sorts of code injection attacks if you're not very careful.

    A safer solution would be to match the proposed operator against a predefined white list and then call a corresponding bit if code with the operator hard - coded.

    C.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题