FAQ
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

Search Discussions

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupphp-notes @
categoriesphp
postedMay 15, '13 at 10:36p
activeMay 15, '13 at 10:36p
posts1
users1
websitephp.net

1 user in discussion

Nathan: 1 post

People

Translate

site design / logo © 2019 Grokbase