Purpose of a function in PHP

Sometimes code can get a bit unwiedly — you can tell that our simple little PHP file is starting to get more & more complex.

This is a simple example, but what happens when you continue to add more & more code? You guessed it — it starts to become harder to update code because it takes longer to find, and updates start to become error prone. Since everything resides in a single file, one little mistake will take down our entire app.

The first step progressing into a more complex, but organized code filesystem & structure is to start combining related code together, and you can do this with a function.

A function just encapsulates a little piece of code. Functions are meant to be extremely small, and only carry out one single, specific task.

There is a design pattern known as the “single responsibility principle”, or SRP. The idea behind this is that every piece of a program, such as a class, module or function, should have a single purpose. This keeps blocks of code short & concise, and leads to easier debugging.

When starting out, you don’t need to obsess over the single responsibility principle, but if you generally follow this concept, your codebase will be more performant, easier to reason about & simpler to update. This will drastically slim down single files of PHP and naturally organize your code in a more efficient manner.

Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock