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\'
$a = 4;
eval('$condition=($a == 4)?true:false;');
if($condition){ echo "Yes"; }else{ echo "No"; }
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;
}
}
As far as I know it is not possible and since there is no reference about callback on operators in PHP documentation, http://www.php.net/manual/en/language.operators.php
instead of using eval, I would redefine each operators in global functions and use php callbacks How do I implement a callback in PHP?
As Michael Krelin suggests you could use eval - but that potentially enables a lot of code injection attacks.
You can't substitute a variable for an operator - but you can substitute a variable for a function:
function is_equal($a, $b) {
return $a==$b;
}
function is_same($a, $b) {
return $a===$b;
}
function is_greater_than($a, $b)
....
$compare='is_equal';
if ($compare($a, $b)) {
....
C.
How about a small class:
class compare
{
function is($op1,$op2,$c)
{
$meth = array('===' => 'type_equal', '<' => 'less_than');
if($method = $meth[$c]) {
return $this->$method($op1,$op2);
}
return null; // or throw excp.
}
function type_equal($op1,$op2)
{
return $op1 === $op2;
}
function less_than($op1,$op2)
{
return $op1 < $op2;
}
}