1. 30
    Purpose of a function in PHP
    1m 34s

Purpose of a function in PHP

Mark Shust
InstructorMark Shust

Share this video with your friends

Send Tweet
Published 9 months ago
Updated 8 months ago

Sometimes you need to group together pieces of code. That's what functions are for! In this lesson, we'll learn all about them.

Instructor: [0:00] Sometimes code can get a bit unwieldy. You can tell that our simple little PHP script is starting to get more and more complex.

[0:09] This is a simple example, but what happens when we continue to add more and more code? You guessed it. It starts to become harder to update code, because it takes longer to find that specific area of code that you want to reference, and updates start to become more error prone. Since everything resides in a single file, one little mistake can take down our entire app.

[0:33] The first step progressing into a more complex, but organized code and file system and structure is to start combining related code together, and you can do this with a function.

[0:44] 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.

[1:00] 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 and concise and leads to easier debugging.

[1:13] When starting out, you don't need to obsess over the single responsibility principle, but if you generally follow this concept, your code will be more performant, easier to reason about, and simpler to update. This drastically slims down single files of PHP and naturally organizes your code in a more efficient manner.