[web-php] master: Enhancement: Extract constants to avoid mutable global state

From: Date: Sat, 09 Jul 2022 12:09:41 +0000
Subject: [web-php] master: Enhancement: Extract constants to avoid mutable global state
Groups: php.webmaster 
Request: Send a blank email to php-webmaster+get-30318@lists.php.net to get a copy of this message
Author: Andreas Möller (localheinz) Committer: GitHub (web-flow) Pusher: cmb69 Date: 2022-07-09T14:03:19+02:00 Commit: https://github.com/php/web-php/commit/acb371e45256bf22c113edfbdfd26a3b38e5f10e Raw diff: https://github.com/php/web-php/commit/acb371e45256bf22c113edfbdfd26a3b38e5f10e.diff Enhancement: Extract constants to avoid mutable global state Closes GH-626. Changed paths: M manual/spam_challenge.php Diff: diff --git a/manual/spam_challenge.php b/manual/spam_challenge.php index cd74ce596..2bba1b056 100644 --- a/manual/spam_challenge.php +++ b/manual/spam_challenge.php @@ -1,7 +1,7 @@ <?php // simple and stupid SPAM protection (using little challenges) -$nums = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'); +const NUMS = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'); function plus($a, $b) { return $a + $b; @@ -27,7 +27,7 @@ function print_prefix($name, $a, $b) { return "$name($a, $b)"; } -$challenges = array( +const CHALLENGES = array( // name, print, generator array('max', 'print_prefix'), array('min', 'print_prefix'), @@ -35,16 +35,14 @@ function print_prefix($name, $a, $b) { array('plus', 'print_infix', 'gen_plus'), ); - // generate a challenge function gen_challenge() { - global $challenges, $nums; - $c = $challenges[rand(0, count($challenges)-1)]; + $c = CHALLENGES[rand(0, count(CHALLENGES)-1)]; $a = rand(0, 9); - $an = $nums[$a]; + $an = NUMS[$a]; $b = isset($c[2]) ? $c[2]($a) : rand(0, 9); - $bn = $nums[$b]; + $bn = NUMS[$b]; return array($c[0], $an, $bn, $c[1]($c[0], $an, $bn)); } @@ -52,19 +50,17 @@ function gen_challenge() { // test an answer for validity function test_answer($name, $an, $bn, $answer) { - global $challenges, $nums; - - foreach ($challenges as $x) { + foreach (CHALLENGES as $x) { if ($x[0] === $name) { $c = $x; break; } } - $a = array_search($an, $nums); - $b = array_search($bn, $nums); + $a = array_search($an, NUMS); + $b = array_search($bn, NUMS); if (empty($c) || $a === false || $b === false) return false; - return ($nums[$c[0]($a, $b)] === $answer); + return (NUMS[$c[0]($a, $b)] === $answer); }

« previous php.webmaster (#30318) next »