10 Ways to Use Functions in Your Code to Become a Better PHP Developer

Tomasz Dobrowolski
5 min readMar 22, 2022
Photo by Remy_Loz on Unsplash

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:

  1. Getting song information using the song ID.
  2. Looping through the array of categories in the song information and saving it to an array.

We can split this into two functions like so:

public function getCategoriesFromSongID(int $songId): array
{
$songInformation = $this->getSong($songId);
return $this->getCategoriesFromArray($songInformation['categories']);
}
private function getCategoriesFromArray(array $categories): array 
{
$arrayOfCategories = [];
foreach ($categories as $category){
array_push($arrayOfCategories, $category);
}
return $arrayOfCategories;
}

2. Functions should be small enough to understand in a few minutes

A large function takes time to read through.

It likely has too many levels of abstraction and has a few sections of code which do different tasks.

--

--

Tomasz Dobrowolski

I break down Software Engineering and Tech concepts | Backend Engineer 🐘