User functions

Despite the fact that PHP comes with such a large array of functions to perform all sorts of tasks, you are likely to want to create your own functions when the need arises. Whether it is because you find yourself doing the same thing very often, or perhaps it is because you want to share code across projects - user functions are for you.

You can give your functions whatever name you like - they follow the same guidelines (without the $) as PHP's variable. Note, though, that you may not redefine PHP's built-in functions.

The simplest user function in PHP looks something like this:

<?php
    function foo() {
        return 1;
    }

    print foo();
?>

As you can see, you define your functions with the function keyword, followed by the name of the function and two parentheses. The actual code your function will execute lies between braces - in our example function $foo our sole line of code is "return 1"; we will get onto that in a moment.

After the function definition, we can treat foo() like any other function, as seen in line four where we print out the value it returns. And what value does it return? Well, unsurprisingly, a function returns its return value .

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Return values >>

Previous chapter: Altering the execution environment

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.