1. 31
    Create a function in PHP
    1m 52s

Create a function in PHP

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet
Published 2 years ago
Updated 2 years ago

In this lesson, we will go over how to create a function with proper syntax in PHP with the function keyword.

Instructor: [0:00] 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 by moving it to its own function.

[0:15] We'll start by creating a new function at the top of the file with the function keyword. It's good practice to put all functions at or near the top of files.

[0:27] 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 call this getPosts.

[0:50] It's common to use camel case when naming functions, which is the first word lowercase, and the first letter of every subsequent word capitalized.

[1:01] You can name functions just about however you wish as long as it doesn't start with a number or odd character. Common convention and practice is to use standard camel case names. If you are wondering what to name your function, you can also name it with an action object. The action here is get and the object is posts.

[1:25] Next comes an open and closed parenthesis, and then an open and closed curly bracket. These brackets segment out a code of this function so everything within these brackets belongs to it. It's also recommended to place a line break after the closing parenthesis and before this first curly bracket, just so you can easily tell where the function starts and ends.

egghead
egghead
~ an hour ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today