3

Is is possible? Something like (which doesn't work) :

$prototype = array(
    'ext' => function ($args)
    {
        $ext = NULL;
        if (in_array(func_get_arg(0), array('js', 'css')))
            return $ext;
        else
            return 'js';
    },
);
4
  • have you tried? did it give an error? Do you want "yes" for an answer? Add more information. Commented Aug 9, 2011 at 14:27
  • 1
    It works fine for me (PHP 5.3.6). Anonymous functions were introduced in PHP 5.3, so make sure you have upgraded. Commented Aug 9, 2011 at 14:27
  • It's your syntax that errors =). Remove the , after the last }. Commented Aug 9, 2011 at 14:31
  • @Tim Cooper you're right, I was using 5.2.x without knowing it :) Commented Aug 9, 2011 at 14:55

2 Answers 2

4

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
?>
Sign up to request clarification or add additional context in comments.

3 Comments

So you can cast it to an object (there is no error). You get an error later because you're using an undefined method, because there is no method named "bar"; there is a field named "bar". i.e. $temp = $obj->$bar; $temp(); Fields and methods are completely separate in PHP.
@newacct, could you suggest a better wording in that case please? :)
Another limitation is that if that array is part of a property initializer, remember that complicated expressions won't work, which includes anonymous functions.
4

It certainly is:

<?php
$array = array(
        'func' => function($a) {
                return $a + 2;
        }
);
echo $array['func'](3);
?>

This will give you 5 =)!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.