Create a function in PHP

To create a function, you need to first decide which piece of code belongs in it.

Something that takes up a large portion of this file is this $posts array. Let’s encapsulate this chunk of code in it’s own function.

Let’s start creating a function with the function keyword at the top of the file. It’s good practice to put all functions at or near the top of files. Next comes the name of the function.

One of the hardest things in programming, especially with creating functions, is figuring out how to name it. Regular functions have a name that is specific to the task it carries out. Since we want to essentially return a list of posts in this first function, let’s name this getPosts.

It’s common to use camelCase when naming functions, which is the first word lowercase, and the first letter of every subsequent word capitalized. You can name functions just about however you wish as long as it doesn’t start with a number or odd character, but common convention and practice is to use standard camelCase names.

If you are wondering what to name your function, you can also name it with an actionObject. So the action here is get, and the object here is Posts.

Next comes an open & closed curly bracket. These brackets segment out the code of this function, so everything within these brackets belongs to this function. It’s also recommended to place a line break after the closing parenthesis and before the first curly bracket, so you can easily collapse code within code editors.

function getPosts()

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