{ return $pup1->name == $pup2->name ? 0 : ($pup1->name < $pup2->name ? -1 : 1); } function sortPupsByBreed($pup1, $pup2) { return $pup1->breed == $pup2->breed ? 0 : ($pup1->breed < $pup2->breed ? -1 : 1); } function sortPupsByWeight($pup1, $pup2) { return $pup1->weight == $pup2->weight ? 0 : ($pup1->weight < $pup2->weight ? -1 : 1); } function sortPupsByPersonality($pup1, $pup2) { return $pup1->personality == $pup2->personality ? 0 : ($pup1->personality < $pup2->personality ? -1 : 1); } $sort_function = getSortFunction($selected_sort); // Default sort is by date added if ($sort_function != "") { usort($pups, $sort_function); } ?> <!-- Header --> <?php include "files/header.php"; ?> <!-- Navigation Bar --> <div id='navbar-items'> <h2 id='add-title' class=<?php echo getClass('index.php');
$timeOfDay = "morning"; return function ($name) use(&$timeOfDay) { $timeOfDay = ucfirst($timeOfDay); return "Good {$timeOfDay}, {$name}!"; }; } $greetingFunction = getGreetingFunction(); echo $greetingFunction("Fred"); // Displays "Good Morning, Fred!" $people = array(array("name" => "Fred", "age" => 39), array("name" => "Sally", "age" => 23), array("name" => "Mary", "age" => 46)); function getSortFunction($sortKey) { return function ($personA, $personB) use($sortKey) { return $personA[$sortKey] < $personB[$sortKey] ? -1 : 1; }; } echo "Sorted by name:<br><br>"; usort($people, getSortFunction("name")); print_r($people); echo "<br>"; echo "Sorted by age:<br><br>"; usort($people, getSortFunction("age")); print_r($people); echo "<br>"; ?> </pre> <?php require_once '../../includes/footer.php'; ?>
}; ## Criando sua própria função com callback $names = array("Marco", "Hiolanda", "Gabriel", "Jeff"); function iteratorTabajara($array, $callback = false) { if (is_callable($callback)) { foreach ($array as $value) { call_user_func($callback, $value); } } } $myNameIs = function ($name) { echo "Meu nome eh {$name}\n"; }; iteratorTabajara($names, $myNameIs); ## Closure High Level $people = array(array("nome" => "Marco", "idade" => 23), array("nome" => "Hiolanda", "idade" => 25)); function getSortFunction($sortKey) { return function ($personA, $personB) use($sortKey) { return $personA[$sortKey] < $personB[$sortKey] ? -1 : 1; }; } echo "Ordenado por nome:<br><br>"; usort($people, getSortFunction("nome")); print_r($people); echo "<br>"; echo "Ordenado por idade:<br><br>"; usort($people, getSortFunction("idade")); print_r($people); echo "<br>";