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

 Methods

Creates a callable returning the given expression.

__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

Parameters

$expression

callablestring

Exceptions

\InvalidArgumentException When $expression not of expected type
\LogicException When $expression does not form valid PHP code

Convenience method to execute the the manufactured callable from the object itself.

__invoke() : mixed

Returns

mixed

Get the callable manufactured for this expression.

getCallable() : callable

Returns

callable

Given a string expression, turn that into an anonymous function.

makeCallable($expression) 
Static

Cache the result, so as to keep memory impacts low.

Parameters

$expression

Exceptions

 Properties

 

In memory cache of built expressions.

$map : \Haldayne\Boost\Map

Default

array()
Static
 

Manufactured callables all have this formal signature, which allows up to 10 parameters to be passed in, accessible as $_N, where 0 <= N <= 9.

$signature : 

Default

'$_0=null, $_1=null, $_2=null, $_3=null, $_4=null,$_5=null, $_6=null, $_7=null, $_8=null, $_9=null'
Static