I\'m building a PHP class with a private member function that returns a string value such as:
\'true && true || false\'
to a public
Just stumbled upon this question, but being fairly uneasy about using eval, I decided to keep looking for a better solution.
What I discovered is yet another wonderful use for PHP's filter_var function, when passing in the FILTER_VALIDATE_BOOLEAN flag (of which there are many).
This "one line" function seems to do well at safely converting a string (or other) object to a boolean:
And, a little testing:
/**
* Let's do some testing!
*/
$tests = array (
"yes",
"no",
"true",
"false",
"0",
"1"
);
foreach($tests as $test) {
$bool = parse_boolean($test);
echo "TESTED: ";
var_dump($test);
echo "GOT: ";
var_dump($bool);
echo "\n\n";
}
Output:
/*
TESTED: string(3) "yes"
GOT: bool(true)
TESTED: string(2) "no"
GOT: bool(false)
TESTED: string(4) "true"
GOT: bool(true)
TESTED: string(5) "false"
GOT: bool(false)
TESTED: string(1) "0"
GOT: bool(false)
TESTED: string(1) "1"
GOT: bool(true)
*/
I haven't looked deep enough, but it's possible that this solution relies on eval down the line somewhere, however I'd still side with using those over plain evaling since I assume that filter_var would also handle sanitizing any input before piping it through eval.