Last active
July 6, 2021 08:45
-
-
Save guanguans/b70858b7b3db898f0a4da82d5e89d063 to your computer and use it in GitHub Desktop.
memoization.php
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 | |
| if (! function_exists('memoization')) { | |
| /** | |
| * 记忆录 | |
| * | |
| * @param callable $callback | |
| * @param ...$parameter | |
| * | |
| * @return mixed | |
| */ | |
| function memoization(callable $callback, ...$parameter) | |
| { | |
| $parameters = array_merge((array)$callback, $parameter); | |
| $uniqueKey = md5(array_reduce($parameters, function ($carry, $parameter){ | |
| return $carry.(is_object($parameter) ? spl_object_hash($parameter) : serialize($parameter)); | |
| }, '')); | |
| global $memoize0411bbf538f3d60ccbdfa6c6b867b979; | |
| // isset($memoize0411bbf538f3d60ccbdfa6c6b867b979[$uniqueKey]) or $memoize0411bbf538f3d60ccbdfa6c6b867b979[$uniqueKey] = call_user_func_array($callback, $parameter); | |
| if (! isset($memoize0411bbf538f3d60ccbdfa6c6b867b979[$uniqueKey])) { | |
| $memoize0411bbf538f3d60ccbdfa6c6b867b979[$uniqueKey] = call_user_func_array($callback, $parameter); | |
| } | |
| return $memoize0411bbf538f3d60ccbdfa6c6b867b979[$uniqueKey]; | |
| } | |
| } | |
| var_dump(memoization(function (){ | |
| return rand(111111, 999999); | |
| })); | |
| var_dump(memoization(function (){ | |
| return rand(111111, 999999); | |
| })); | |
| var_dump(memoization(function (){ | |
| return rand(111111, 999999); | |
| })); | |
| // int(638411) | |
| // int(638411) | |
| // int(638411) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment