views:

307

answers:

3

I'm building a PHP class with a private member function that returns a string value such as:

'true && true || false'

to a public member function. (This string is the result of some regex matching and property lookups.) What I'd like to do is have PHP parse the returned logic and have the aforementioned public function return whether the boolean result of the parsed logic is true or false.

I tried eval(), but I get no output at all. I tried typecasting the boolean returns...but there's no way to typecast operators...hehe Any ideas? (Let me know if you need more information.)

+2  A: 

Let's assume eval() is an ok/good solution in your case.

class Foo {
  private function trustworthy() {
    return 'true && true || false';
  }

  public function bar() {
    return eval('return '.$this->trustworthy().';');
  }
}

$foo = new Foo;
$r = $foo->bar();
var_dump($r);

prints bool(true)

VolkerK
Thanks for your help; I was indeed forgetting the 'return'...hehe
TheOddLinguist
+2  A: 

eval() will work perfectly fine for this, but remember you have to tell it to return something.

$string = "true && true || false";
$result = eval("return (".$string.");"); // $result will be true

Also make sure you sanitize any user inputs if putting them directly into an eval().

Rich Adams
Thanks; I was forgetting the 'return'. The string is the result of a rather tight regex, so I think I'll be fine. I'll re-assess the sanitizing now that this is working. Thanks again.
TheOddLinguist
A: 

(string) true && true || false

wiiman