Ryre
Ryre

Reputation: 6181

Can I use a function in place of a variable?

I'm curious if PHP can handle code like this, or if I'm using the wrong syntax:

$someString = implode(', ', function(){
    return array('a', 'b', 'c');
});

With the desired output being a, b, c.

I'm using PHP version 5.3.3.

Upvotes: 1

Views: 48

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173642

The second parameter to implode() takes an array, so you have to immediately execute the closure:

$someString = implode(', ', call_user_func(function(){
    return array('a', 'b', 'c');
}));

It would arguably be nicer to have this:

$someString = implode(', ', function(){
    return array('a', 'b', 'c');
}());

But that causes a parse error.

Another acceptable way:

$myGenerator = function(){
    return array('a', 'b', 'c');
};

$someString = implode(', ', $myGenerator());

Upvotes: 1

Related Questions