PHP : anonymous function in associative array
Is is possible? Something like (which doesn't work) :
$prototype = array(
'ext' => function ($args)
{
$ext = NULL;
if (in_开发者_如何学JAVAarray(func_get_arg(0), array('js', 'css')))
return $ext;
else
return 'js';
},
);
Yes. The only limitation is that you can't cast it to an object.
<?php
$foo = array(
'bar' => function($text)
{
echo $text;
}
);
$foo['bar']('test'); //prints "test"
$obj = (object)$foo;
$obj->bar('test'); //Fatal error: Call to undefined method stdClass::bar() in /code/REGnPf on line 11
?>
It certainly is:
<?php
$array = array(
'func' => function($a) {
return $a + 2;
}
);
echo $array['func'](3);
?>
This will give you 5 =)!
精彩评论