note 112192 added to functions.anonymous
| From: | nathan at crause dot name | Date: | Wed, 15 May 2013 22:35:53 +0000 |
| Subject: | note 112192 added to functions.anonymous | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-194815@lists.php.net to get a copy of this message | ||
One item not mentioned anywhere is how to invoke an anonymous function "in-line".
To explain what I mean, let me use an actual example. Instead of creating code like this:
<?php
$wording = ($from == 0 && $to == 0
? '< 1 Year'
: ($to == 9999
? ($from - 1) . '+ Years'
: "$from - $to Years"));
?>
You might, instead, want to use an anonymous function right in the assignment line. However, doing:
<?php
$wording = function() use ($from, $to) { ... }
?>
would actually assign $wording to the Closure instance, not actually execute the function.
The best way to do this that I've found is:
<?php
$wording = call_user_func(function() use ($from, $to) {
if ($from == 0 && $to == 0) return '< 1 Year';
if ($to == 9999) return ($from - 1) . '+ Years';
return "$from - $to Years";
});
?>
It's a little longer than the first code sample, but I think it's more readable, and using
this methodology opens up the ability to use more complex means of calculating a value without
filling the variable scope with a bunch of temporary variables.
----
Server IP: 69.147.83.199
Probable Submitter: 184.71.0.166
----
Manual Page -- http://php.net/manual/en/functions.anonymous.php
Edit -- https://master.php.net/note/edit/112192
Del: integrated -- https://master.php.net/note/delete/112192/integrated
Del: useless -- https://master.php.net/note/delete/112192/useless
Del: bad code -- https://master.php.net/note/delete/112192/bad+code
Del: spam -- https://master.php.net/note/delete/112192/spam
Del: non-english -- https://master.php.net/note/delete/112192/non-english
Del: in docs -- https://master.php.net/note/delete/112192/in+docs
Del: other reasons-- https://master.php.net/note/delete/112192
Reject -- https://master.php.net/note/reject/112192
Search -- https://master.php.net/manage/user-notes.php