Created
October 5, 2019 06:23
-
-
Save caironm/3b2fd0238c384643dadd6eef39219884 to your computer and use it in GitHub Desktop.
Closure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Simulation configuration | |
$config['uppercase'] = true; | |
$lambda = function ($first, $second) { | |
return $first + $second; | |
}; | |
$result_lambda = $lambda(2, 3); | |
echo $result_lambda; | |
// Resultado: 5 | |
$closure = function ($message) use ($config) { | |
if(isset($config['uppercase']) && $config['uppercase'] == true) { | |
$message = strtoupper($message); | |
} | |
return $message; | |
}; | |
$result_closure = $closure('Hello world'); | |
echo $result_closure; | |
// Resultado: HELLO WORLD | |
// Using as a callback | |
function firstWord($message, $callback) { | |
$parts = explode(' ', $message); | |
return $callback($parts[0]); | |
} | |
$result_callback = firstWord('Hello World', $closure); | |
echo $result_callback; | |
// Resultado: HELLO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment