清单 10. 良好习惯:带参数的可重用函数
- <?php
- /*
- * Counts the messages with the given severity in the array
- * of messages.
- * @param $messages An array of ResultMessage
- * @return int Count of messages matching $withSeverity
- */
- function countMessages($messages, $withSeverity)
- {
- $matchingCount = 0;
- foreach($messages as $m) {
- if ($m->getSeverity() == $withSeverity) {
- $matchingCount++;
- }
- }
- return $matchingCount;
- }
- /**
- * Counts the number of messages found in the array of
- * ResultMessage with the getSeverity() value of "Error"
- * @param $messages An array of ResultMessage
- * @return unknown_type
- */
- function countErrors($messages)
- {
- return countMessages($messages, "Errors");
- }
- /**
- * Counts the number of messages found in the array of
- * ResultMessage with the getSeverity() value of "Warning"
- * @param $messages An array of ResultMessage
- * @return unknown_type
- */
- function countWarnings($messages)
- {
- return countMessages($messages, "Warning");}
- /**
- * Counts the number of messages found in the array of
- * ResultMessage with the getSeverity() value of "Warning"
- *
- * @param $messages An array of ResultMessage
- * @return unknown_type
- */
- function countInformation($messages)
- {
- return countMessages($messages, "Information");
- }
- $messages = array(new ResultMessage("Error", "This is an error!"),
- new ResultMessage("Warning", "This is a warning!"),
- new ResultMessage("Error", "This is another error!"));
- $errs = countErrors($messages);
- echo("There are " . $errs . " errors in the result.\n");
- ?>
结束语
如果您在编写 PHP 代码的过程中养成本文讨论的良好习惯