Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function as array value

I can't seem to find anything of this, and was wondering if it's possible to store a function or function reference as a value for an array element. For e.g.

array("someFunc" => &x(), "anotherFunc" => $this->anotherFunc())

Thanks!

like image 602
user784446 Avatar asked Feb 25 '12 11:02

user784446


1 Answers

Yes, you can:

$array = array(
    'func' => function($var) { return $var * 2; },
);
var_dump($array['func'](2));

This does, of course, require PHP anonymous function support, which arrived with PHP version 5.3.0. This is going to leave you with quite unreadable code though.

like image 102
Treffynnon Avatar answered Oct 13 '22 17:10

Treffynnon