Functions overview

To begin with, we are going to look at how to use PHP's built-in functions inside your scripts, as you need to be able to call functions before you need to bother learning how to write your own functions!

Calling a function in PHP can be as simple as printing the name of a function with two parentheses, ( and ), after it. Many functions take parameters - values that are used to affect the execution of the function. Furthermore, nearly all functions have a return value - the result of the function - and you can use these return values as parameters to other functions, like this:

func1(func2(func3(), func4()));

Author's Note: Parameters are the variables listed in a function declaration that define what values must be passed in to a function, whereas the actual parameters passed in during a function call are called arguments. Many people use "parameter" and "argument" to mean the same thing, whereas others abide strictly by the technical definition. This book uses the two interchangeably, so you needn't worry about the difference.

While most parameters are required, some are optional - that is, you do not need to supply them. When optional parameters are not supplied, PHP will assume a default value, which is usually the most commonly desired.

When you pass a parameter to a function, PHP actually takes a copy, and uses the copy inside the function. This means that variables you have passed into a function can be changed as often as you like inside that function and they will remain untouched outside the function. To change this behaviour, you can opt to pass a variable in as a reference, which works in the same way as reference assigning - PHP passes the actual variable into the function, and any changes you make to that variable will still be there when the function exits. This script demonstrates the difference:

<?php
    somefunc($foo);
    somefunc($foo, $bar);
    somefunc($foo, &$bar);
    somefunc(&$foo, &$bar);
?>

The first line calls somefunc(), passing in a copy of $foo, the second passes in copies of $foo and $bar, the third passes in a copy of $foo but the original $bar, and the last passes in both the original $foo and $bar. Passing by reference, as with $bar in line three and $foo and $bar in line four, mean that these variables can be changed inside the function, which is often used as a way for functions to return values.

 

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: How to read function prototypes >>

Previous chapter: Functions

Jump to:

 

Home: Table of Contents

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