10 Ways to Use Functions in Your Code to Become a Better PHP Developer
Functions are fundamental to writing code, making it vital that you write them well.
Well-written functions make your code efficient, easy to read and reduce the chance of errors.
Here is a list of advice on writing good functions with PHP examples, as detailed in Robert C. Martin’s book titled Clean Code:
1. Functions should do one thing
As a rule of thumb, functions should have one level of abstraction.
If there is more than one level of abstraction, not only is your code doing too much. It is difficult to understand for the reader and allows the possibility for other programmers to misinterpret the important parts of the code.
Take a function, for example:
public function getCategoriesFromSongID(int $songId): array
{
$arrayOfCategories = [];
$songInformation = $this->getSong($songId);
foreach ($songInformation['categories'] as $category){
array_push($arrayOfCategories, $category);
}
return $arrayOfCategories;
}
This is doing multiple things:
- Getting song information using the song ID.
- Looping through the array of categories in the song information…