I have this code but I am stuck...
$my_var = function (){
return array('hello you');
};
var_dump($my_var); // returns object(Closure)#2 (0) { }
how do I echo $my_var
?
I would assume it would be echo $my_var[0]
; but this does not work.
Fatal error: Cannot use object of type Closure as array in ...
Basically a closure in PHP is a function that can be created without a specified name - an anonymous function. Here's a closure function created as the second parameter of array_walk() . By specifying the $v parameter as a reference one can modify each value in the original array through the closure function.
A closure is a separate namespace, normally, you can not access variables defined outside of this namespace. There comes the use keyword: use allows you to access (use) the succeeding variables inside the closure.
When an object implements this method, it becomes invokable: it can be called using the $var() syntax. Anonymous functions are instances of Closure , which implements __invoke . Or assign it to a local variable: $lambda = $myInstance->lambda; $lambda();
Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.
A closure is a function. Therefore you have to call it, like this :
$myvar();
Since php5.4 with Array Access:
echo $myvar()[0];
$my_var represents a function. You need to call it first to get the return value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With