0

I am passing a condition as a string to my method and I want to use it inside an if statement like so but it doesn't seem to work.

// $condition could be a > or < or == etc...
if (!( $field $condition $value )) {
         //code here
}

Is there a way to do this in PHP. I have tried wrapping $condition in curly brackets but does not work.

many thanks in advance

Martijn
  • 15,791
  • 4
  • 36
  • 68
Marco
  • 624
  • 1
  • 6
  • 21

2 Answers2

3

This is a terrible idea. The best way to handle this is a switch statement.

switch ($condition) {
    case ">":
        return $field > $value;
    case "<"
        return $field < $value;
    default:
        return false;
}

Any other method is going to be a hack, hard to maintain, or insecure.

user1119648
  • 531
  • 1
  • 5
  • 16
  • Yes, my first option was using a switch but I wanted to save some lines of code. this method is implemented to allow the designers to add classes in tables in an easy way. No external user will ever access or input any data – Marco Feb 16 '18 at 13:18
  • 1
    But treat it as if external users someday will. Because than you'll still understand this code in a few months from now – Martijn Feb 16 '18 at 13:19
  • Yes, @Marco, listen to Martijn. Some day, someone will be working on this code and not realize the implications, and then they will allow in some unsanitized user input. Suddenly you are equifax and all your database are belong to them. – user1119648 Feb 16 '18 at 14:49
1

Passing a condition as a string is not recommended, it could lead to majors security breachs.

I would recommand to change your architecture or use some kind of enumeration (this could help you) in addition to a switch case.

Ckankonmange
  • 111
  • 4