Manufactures a callable from a string.
In PHP, a callable can be a function name (as a string), a class or object method specification (as an array [object|string, string], an anonymous function (via create_function), or a closure (function () { ... }). Sadly, the syntax for these callable methods may dwarf the meat of the code to run:
uasort($array, function ($a, $b) { return $a <=> $b; });
// vs. an ideal expression
uasort($array, '$_0 <=> $_1');
This class wraps anonymous functions around string code "expressions", in a reasonably performant manner. Libraries wanting to support concise expressions as arguments to their functions can then use this class to produce that effect:
use Haldayne\Fox\Expression;
function filter(array $array, $expression) {
return array_filter($array, new Expression($expression));
}
print_r(filter([ 'bee', 'bear', 'goose' ], '4 <= strlen($_0)'));
see | |
---|---|
see | |
see | |
see | |
see | |
see | |
package | Haldayne |
__construct(callable|string $expression)
If the expression is already callable, returns it untouched. If the expression is a string, a closure will be wrapped around the string returning it as a single value. In this case, the first 10 positional arguments are available as $_0, $_1, ..., $_9.
$lt = new Expression('$_0 < $_1'); // expressions is a comparison
var_dump($lt(0, 1)); // true
var_dump($lt(1, 0)); // false
var_dump($lt()); // false (null not less than null)
var_dump($lt(-1)); // true (-1 is less than null)
Do not include a return
in your expression.
see | Definition of PHP expression |
---|
callable
string
\InvalidArgumentException |
When $expression not of expected type |
---|---|
\LogicException |
When $expression does not form valid PHP code |
__invoke() : mixed
mixed
getCallable() : callable
callable
makeCallable($expression)
Cache the result, so as to keep memory impacts low.
$map : \Haldayne\Boost\Map
array()
$signature :
'$_0=null, $_1=null, $_2=null, $_3=null, $_4=null,$_5=null, $_6=null, $_7=null, $_8=null, $_9=null'