1

why doesn't this work?

$arr=array(
7,
'h',
function($text){echo $text;}
);

$arr[2]('some text');

I want it to echo 'some text' but it says that there is an unexpected T_FUNCTION.

2 Answers 2

3

Anonymous functions have been added in PHP 5.3.0 to my knowledge. This error seems to indicate that the version you're using doesn't support them.

Sign up to request clarification or add additional context in comments.

1 Comment

I found that I can use create_function() instead
2

Indeed that seems to be the correct answer. I wasn't sure that the function in array syntax would work (even in PHP 5.3.x), so I've just tested it and it does seem to work:

<?php
echo phpversion( ) . ": ";
$foo = array( 
    'test' => function( ) {
        return 'This is my test.';
    }
);

echo $foo['test']( );
?>

That outputs (on my machine, of course):

5.3.2-1ubuntu4.7: This is my test.

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.