Tips for Creating Functions in PHP
- Function names should be verbs.
- Each function's name should accurately reflect what the function does.
- A function should do only what is explicitly implied by its name, and nothing else.
- Each function should perform only one action.
- Use helper functions inside functions.
-
It is better not to make the code of functions longer than
10
-15
lines. - Long functions are better split into a series of helper functions.
-
Use common prefixes in function names:
show
,get
,set
,calc
,create
,change
,check
. - Move duplicate code into functions.
Write what the drawbacks of the following code are and fix them:
<?php
function sum($arr) {
$res = 0;
foreach ($arr as $elem) {
$res += $elem;
}
return $res / count($arr);
}
?>
Write what the drawbacks of the following code are and fix them:
<?php
function func($arr1, $arr2) {
$res1 = 0;
foreach (arr as $elem) {
$res1 += $elem;
}
$res2 = 0;
foreach (arr as $elem) {
$res2 += $elem;
}
return $res1 / $res2;
}
?>
Write what the drawbacks of the following code are and fix them:
<?php
function getSum($arr) {
$res = 0;
foreach ($arr as $elem) {
$res *= $elem;
}
return $res;
}
?>