简体   繁体   中英

What differences are there with closures between PHP 5.3 and 5.4?

I am running PHP 5.3.15 (custom apache/php/mysql stack on OSX) locally, and have the following code, which works just fine:

$my_closure = function($something, $other) use (&$foo, $bar) {
  // watcha doin'? ... stuff.
};

$my_closure('hello', array('one', 'two'));

A coworker is using MAMP with PHP 5.4.x, and is getting the "Function name must be a string" error on the closure call ( $my_closure(...); ).

I can work around this using call_user_func() or call_user_func_array() , but I want to know why this code no longer works on 5.4.x. I think this is either a change in 5.4.x, or an issue with MAMP (in my experience, even more likely!).

There is a somewhat related bug report on php.net that discusses the inability to use a callable array the same way I'm using the closure. The bug's comments do confirm that what I'm doing works fine in 5.3, and also mention implementing the callable array functionality in 5.4; perhaps the implementation introduced a regression bug? Any details/suggestions would be appreciated.

And yes, I'd love to use Vagrant for everyone on the team to have identical environments, but alas, no dice.

Let your friend double check he's running 5.4. Your syntax is perfectly ok for both 5.3 and 5.4 (and I daresay any future version of PHP)

You can test your code in PHP 5.4 here (run echo phpversion(); to confirm it's indeed 5.4). As you will see it does not raise any errors.

I too tried your code here and it works fine in PHP5.4.

Do you by chance have eAccelerator enabled with PHP5.4 in your Mamp configuration? The eAccelerator caching software ships with Mamp for PHP versions prior to PHP5.5. I suggest disabling eAccelerator as another developer did in this article . The article alleges that eAccelerator simply has not kept up with all the changes that PHP has experienced. Another user also experienced the same problem when using PHP5.4 with eAccelerator; see here . And, Mamp no longer includes eAcclerator with PHP starting with versions PHP5.5 on up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM