0

Currently I am doing this:

$f = create_function(null, somecode);
$f();

Is there anyway to not assign it to a variable, but instead directly execute it? I'm thinking of something like

create_function(null, somecode)();

But this is not working unfortunately. Do not ask me why I want to do this, there is no special reason, I was just wondering this the other day.

Blub
  • 3,762
  • 1
  • 13
  • 24
  • What PHP version are you on? – PeeHaa May 14 '14 at 10:16
  • 1
    Why are you still using `create_function` instead of using anonymous functions? – Barmar May 14 '14 at 10:16
  • 2
    Depends on PHP's version you use. If you use > 5.3 then yes, otherwise - no. But it looks like you use outdated PHP version, so probably - no – Yang May 14 '14 at 10:18
  • 1
    @djay why not? just `call_user_func(create_function(null, code))`. Will work in 5.2 (probably, even in PHP 4). I have no idea why to do that - if storing __callable thing__ is not an intention, then it's `eval()` which can be used to direct code execution (the question how justified is that is another story.. ) – Alma Do May 14 '14 at 10:24
  • @AlmaDo because he's too lazy to write `call_user_func(create_function(null, code))` - its even longer than `create_function(null, somecode); $f();`. That's why – Yang May 14 '14 at 10:36
  • But OP's request has nothing to do with length. He just wants to get rid of variable (that may have sense for me if it's about execution of one line in debugger, for example, but still something is wrong if direct code evaluation is needed) – Alma Do May 14 '14 at 10:38
  • @AlmaDo is right, I just wanted to get rid of variable. I was wondering if it is possible. It has no practical value to me, it was just my curiosity. But with call_user_func() is a good solution (although not as easy as I imagined with just simple () :P) – Blub May 14 '14 at 10:44

2 Answers2

2

You can just execute an anonymous function...

call_user_func(function(){
    echo 'I am a function!';
});

PHP VERSION > 5.3

Ian Brindley
  • 2,197
  • 1
  • 19
  • 28
0

Normal closures, > PHP 5.3:

$func = function($str) { echo $str; };

$func('hello world');

If you directly want to execute code, why would you even want to put it into a function? Turning the above code into the following is equivalent to instantly executing:

echo 'hello world';
Daniel W.
  • 31,164
  • 13
  • 93
  • 151