Dynamic Comparison Operators in PHP

后端 未结 11 712
挽巷
挽巷 2020-12-03 11:24

Is it possible, in any way, to pass comparison operators as variables to a function? I am looking at producing some convenience functions, for example (and I know this won\'

11条回答
  •  生来不讨喜
    2020-12-03 12:01

    The top answer recommends a small class, but I like a trait.

    trait DynamicComparisons{
    
    private $operatorToMethodTranslation = [
        '=='  => 'equal',
        '===' => 'totallyEqual',
        '!='  => 'notEqual',
        '>'   => 'greaterThan',
        '<'   => 'lessThan',
    ];
    
    protected function is($value_a, $operation, $value_b){
    
        if($method = $this->operatorToMethodTranslation[$operation]){
            return $this->$method($value_a, $value_b);
        }
    
        throw new \Exception('Unknown Dynamic Operator.');
    }
    
    private function equal($value_a, $value_b){
        return $value_a == $value_b;
    }
    
    private function totallyEqual($value_a, $value_b){
        return $value_a === $value_b;
    }
    
    private function notEqual($value_a, $value_b){
        return $value_a != $value_b;
    }
    
    private function greaterThan($value_a, $value_b){
        return $value_a > $value_b;
    }
    
    private function lessThan($value_a, $value_b){
        return $value_a < $value_b;
    }
    
    private function greaterThanOrEqual($value_a, $value_b){
        return $value_a >= $value_b;
    }
    
    private function lessThanOrEqual($value_a, $value_b){
        return $value_a <= $value_b;
    }
    
    }
    

提交回复
热议问题