Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php Closure object how to read it?

Tags:

closures

php

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 ...

like image 804
Val Avatar asked Oct 13 '12 09:10

Val


People also ask

What is PHP closure object?

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.

What is closure in PHP and why does it use use identifier?

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.

How do you call 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();

Is closure and anonymous function same?

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.


2 Answers

A closure is a function. Therefore you have to call it, like this :

$myvar();

Since php5.4 with Array Access:

 echo   $myvar()[0];
like image 74
pce Avatar answered Sep 30 '22 10:09

pce


$my_var represents a function. You need to call it first to get the return value.

like image 43
phant0m Avatar answered Sep 30 '22 08:09

phant0m