Creating PHP Functions

Video loading...

Join Drupalize.Me to watch this video

Join today and gain instant access to our entire video library.

Log in Sign up
  • 0:06
    LEANNA PELHAM (VOICEOVER): You've come a long way already
  • 0:09
    which has included using a bunch of built-in functions.
  • 0:12
    Now it's time to make our own.
  • 0:14
    The first thing our PHP code does is read our pets.JSON file and decode
  • 0:19
    it into an array which we set in our pets variable.
  • 0:23
    Let's invent a new function called get_pets that
  • 0:25
    will do this work for us and return the finished array.
  • 0:29
    Custom functions are used just like core PHP functions, so, eventually,
  • 0:33
    I want our code to look like this.
  • 0:36
    Oh, and those two slash marks are one of two ways
Loading ...

Creating PHP Functions

Loading...

You've come a long way already, which has included using a bunch of existing, built-in functions. Now it's time to make our own! The first thing our PHP code does right now is read our pets.json file and decode it into an array, which we set on our $pets variable. Let's invent a new function called get_pets() that will do this work for us and return the finished array. Putting this into a function lets us reuse this logic whenever we want, in other places in our code, without having to write it all out again. This also makes organizing and updating our code more straight-forward and simple.

Downloads: 
Log in or sign up to download companion files.

Additional resources:
There are no resources for this video. If you believe there should be, please contact us.