Val
Val

Reputation: 17522

php Closure object how to read it?

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

Upvotes: 5

Views: 6465

Answers (3)

pce
pce

Reputation: 5931

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

$myvar();

Since php5.4 with Array Access:

 echo   $myvar()[0];

Upvotes: 10

phant0m
phant0m

Reputation: 16905

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

Upvotes: 1

Man Programmer
Man Programmer

Reputation: 5356

try print_r it will print array or object

print_r($my_var);

Upvotes: -1

Related Questions