I know it's possible to do the following with PHP 5.3 (anonymous functions), but is there a similar alternative in older PHP version (pre-5.3)?
$exampleArray = array(
'func' => function() {
echo 'this is an example';
}
Is it possible to do this with __call or typecasting the function as an (object) first? Also, I tried making the function un-anonymous by giving it a name, but this didn't seem to work.
Yes it is possible to create lamda functions with PHP pre 5.3 using create_function. It isn't possible to create closures though which your question mentions but doesn't actually use.
A closure is a lamda function that has access (closes over) a variable from it's enclosing scope:
A lamda function is an anonymous function useful for storing in a variable or passing as an argument etc. You can use
create_function()
pre 5.3 like this:If you want to create anonymous in PHP < 5.3, you can use
create_function
function. Also Here is interesting information about callbacks (may be usefull).Example using
create_function
But you can do the same thing liek code above with alternative way:
Code above creates function which does something, then we store function name in variable (can be passed as parameter, etc.).
Calling function when we know only it's name:
First way
Alternative
So example that connects everything above:
And use of above function:
Returns:
Links:
create_function()
call_user_func()
is_callable()
create_function
What about just creating a class with 'func' as a class method? Would work pre or post 5.3.