5

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

1
  • 1
    Someone at PHP headquarters should be keelhauled for that error message. It demonstrates a dramatic lack of understanding of closure. Commented Oct 15, 2012 at 6:38

3 Answers 3

10

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

$myvar(); 

Since php5.4 with Array Access:

 echo $myvar()[0]; 
Sign up to request clarification or add additional context in comments.

1 Comment

yes, thank you, just was being stupid :) btw, $myvar()[0] I have read that will be available on php I can't remember which version, but I defenetly like the future for PHP.
1

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

Comments

-1

try print_r it will print array or object

print_r($my_var); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.