2

I want to create and execute a closure within a string in PHP and it's not liking the way that I do it.

This code doesn't work...

echo ( 'Hello, ' . (function($s) { return $s; })('World!') );

Yet, this is completely valid and works as intended...

$f = (function($s) { return $s; });
echo ( 'Hello, ' . $f('World!') );

Why won't the first one work and is there a way to do it in one line (not because I think it's efficient, because I'm sure it's not)?

  • possible duplicate of [Self Executing functions in PHP5.3?](http://stackoverflow.com/questions/3865934/self-executing-functions-in-php5-3) – Ja͢ck Aug 27 '12 at 20:38

2 Answers2

2

You may want to take a look at Self Executing functions in PHP5.3?.

Essentially, no self-invoking with "(...)()" until (maybe) sometime in 5.4.

https://wiki.php.net/rfc/fcallfcall

Community
  • 1
  • 1
simshaun
  • 21,263
  • 1
  • 57
  • 73
  • @KevinHikaruEvans because the feature status is still 'under discussion' - https://wiki.php.net/rfc/fcallfcall – Ja͢ck Aug 27 '12 at 20:38
  • Oh alright, thanks. I guess I'll have to declare functions the old fashioned way then. –  Aug 27 '12 at 20:39
  • Sorry for the confusion. Added the link provided from the top answer in the linked question. As Jack said, the feature is still just discussion, – simshaun Aug 27 '12 at 20:40
0

I believe that's only possible in PHP 5.4: http://php.net/manual/en/migration54.new-features.php

Ariel
  • 25,995
  • 5
  • 59
  • 69