Cleaner Code with 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:00
    Cleaner Code with PHP Functions
  • 0:01
    with Leanna Pelham
  • 0:08
    Hey, I have an idea.
  • 0:10
    Let's clean up our code a little bit by creating
  • 0:12
    a save_pets() function in functions.php.
  • 0:22
    Copy in the two lines that encode the $pets
  • 0:24
    array and writes the file.
  • 0:32
    My editor is highlighting the $pets variable, because it's undefined.
  • 0:36
    A function only has access to the variables you create inside of it.
  • 0:41
    And yep, there's definitely no $pets variable here.
Loading ...

Cleaner Code with PHP Functions

Loading...

Our form is working well now, and to finish up, in this tutorial we're going to clean up and reorganize our code a little bit by moving things into a new custom function, called save_pets(). This won't change how the form works, but moving logic into functions gives us two advantages, re-usable code, and making it clearer what the code we've written does, and is intended for.

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