5
Employing functions
This chapter demonstrates how to create re-usable blocks of code in functions.
Defining functions
PHP provides many built-in functions that can be called by name in your scripts to execute pre-defined actions, such as the array sorting functions described here . Additionally, you may create your own custom functions to execute specified actions when called. This usefully allows PHP scripts to be modularized into sections of code that are easier to understand and maintain.
Your custom function names may contain any combination of letters, numbers and the underscore character, but must begin with a letter or an underscore. Understandably, to avoid conflict the name may not duplicate an existing built-in function name, so for example you may not create a custom function named “sort”.
Unlike PHP variables, function names are case-insensitive so cube() , Cube() and CUBE() can all reference the same function. Nonetheless,- it is recommended you always use the same case as that used to name the function in the function definition.
A function definition is created in a PHP script simply by stating its name after the function keyword, followed by parentheses and curly brackets (braces) containing the statements to be executed each time that function gets called:
function function_name ( )
{
statement-to-be-executed ;
statement-to-be-executed ;
statement-to-be-executed ;
}
PHP variable names are case-sensitive, but PHP function names are not.
A PHP script can then call upon a defined function by name using function_name ( ); to execute the statements it contains whenever required. Although the interpreter runs the script from top to bottom, a function call can appear before the function definition. This is not good programming practice, however, so you should define functions before they are called.
Functions may contain any valid PHP script code and may even contain a further function definition. In that case, the inner function will not exist until the outer function has been called.
function.php
Begin a PHP script with a statement to define a function
<?php
function greet ()
{
echo ‘Hello User!<br>’ ;
}
Next, add a statement to call the function defined in the previous step, to have it execute its statement
greet () ;
Now, define another function that contains an inner function definition and a further statement
function outer ()
{
function inner ()
{
echo ‘Inner function called.<br>’ ;
}
echo ‘Inner function created.<br>’ ;
}
Finally, add statements to call each of the functions defined in the previous step
outer () ;
inner () ;
?>
Save the document in your web server’s
/htdocs
directory as
function.php
then open the page via HTTP to see the output from each function call
Remove the call to the outer function to see an undefined function error when the script attempts to call the inner function.
Passing arguments
Data can be passed to functions as “arguments” in the same way you can pass arguments to some built-in PHP functions. For example, the sort() function takes the array to be sorted as its argument. Functions can be created with any number of arguments but when called, data must be supplied for each argument to avoid an error.
Parameters must be specified in the function declaration as a comma-separated list, and argument values passed by the caller as a comma-separated list.
A function accepting arguments is defined by including a comma-separated list of “parameters” within the parentheses after the function name, like this:
function function_name ( $arg_1 , $arg_2 , $arg_3 )
{
statement-to-be-executed ;
statement-to-be-executed ;
statement-to-be-executed ;
}
Parameter names must adhere to the same naming conventions required for PHP variables and should ideally be meaningful, to represent the nature of the data they will be passed. The argument data must be passed by the call in the correct order and can then be used by the statements within that function.
Optionally, the function definition can specify the type of data to be passed from the caller by including a type description before the parameter name. Valid type descriptions include int , float , string , bool , callable and array . When types are specified, a call that attempts to pass an incorrect data type to the function will result in an error.
The ability to specify argument data types is a new feature in PHP 7.
It is important to recognize that by default, argument data is passed “by value”. This means that if a function call specifies a variable name, only a copy of the data within that variable gets passed to the function. Modifying the argument will not affect the original data stored in the variable when it is passed by value.
If you want a function to modify data stored in a variable, specified in a function call, you must pass it “by reference”. This allows the function to operate directly on the original data. Modifying the argument will affect the original data in the variable when it is passed by reference. To ensure that an argument is always passed to a function by reference, you need simply prefix an & ampersand before the parameter name in the function definition.
arguments.php
Begin a PHP script with a statement to initialize two variables with the same integer value
<?php
$a = $b = 5 ;
Next, define a function that accepts two integer arguments – one by value and the other by reference
function modify ( int $val , int & $ref )
{
// Statements to be inserted here.
}
Now, insert statements to output the passed values, then increment those values and display the modified values
echo “Passed values : $val , $ref <br>” ;
$val ++ ;
$ref ++ ;
echo “Incremented values : $val , $ref <hr>” ;
After the function block add a statement to call the function, passing the variable values as arguments
modify ( $a , $b ) ;
Finally, add a statement to display the values now stored in each variable
echo “Stored values : $a , $b ” ;
?>
Save the document in your web server’s
/htdocs
directory as
arguments.php
then open the page via HTTP to see the argument and variable values
The int type description in this example specifies that only integer data values can be passed as arguments to the function.
Varying parameters
Default argument values can optionally be specified in a function definition by assignment to the parameter name, like this:
function function_name ( $arg_1 , $arg_2 = “Default String” )
{
statement-to-be-executed ;
statement-to-be-executed ;
statement-to-be-executed ;
}
This allows a function call to be made that specifies either one or two argument values. If only one argument is specified, it is assigned to the first parameter and the default value is used by the second parameter. Where default values are specified for parameters, they must only appear in the parameter list following (to the right of) parameters that have no specified default value. Otherwise, a call without the correct total number of arguments would cause an error.
If multiple default values are specified there is currently no way to skip a parameter in a function call, to assign an argument value to a particular parameter.
If you need to create a function that will accept an unknown number of arguments, PHP has a special ... “splat” operator for that purpose. This can be used in a function definition like this:
function function_name ( ...$args )
{
statement-to-be-executed ;
statement-to-be-executed ;
statement-to-be-executed ;
}
When the ... splat operator is used to prefix a parameter name in a function definition, multiple arguments can be passed to that parameter to create an array. The array can be traversed like any other array to manipulate the passed in argument values.
Additionally, the ... splat operator can be used to “unpack” an array specified in a function call to pass its element values as individual arguments like this:
function function_name ( $arg_1 , $arg_2 , $arg_3 )
{
echo $arg_1 + $arg_2 + $arg_3 ;
}
$arr = [ 1 , 2 , 3 ] ;
function_name ( ...$arr ) ; # Outputs 6
The ... splat operator is also sometimes known as the “scatter” operator.
parameters.php
Begin a PHP script by defining a function that provides default string values to its two parameters
<?php
function drink ( string $tmp = ‘hot’ , string $flavor = ‘tea’ )
{
// Statement to be inserted here.
}
Next, insert a statement to display its default values or passed in argument values
echo “Drinking $tmp $flavor .<br>” ;
After the function block, add function calls that optionally pass string arguments
drink () ; drink ( ‘iced’ ) ; drink ( ‘cold’ , ‘lemonade’ ) ;
Now, define a function that can accept multiple integer arguments and display their total value
function add ( int ... $numbers )
{
$total = 0 ;
foreach( $numbers as $num ) { $total + = $num ; }
echo “<hr>Total : $total ” ;
}
Finally, after the function block add a statement to call the function in the previous step and pass three values
add ( 1 , 2 , 3 ) ;
?>
Save the document in your web server’s
/htdocs
directory as
parameters.php
then open the page via HTTP to see the argument and default values
You can specify regular positional parameters before a parameter that accepts multiple arguments with the ... splat operator. Only arguments that outnumber the positional elements will be added to the array of the final parameter.
Recognizing scope
When creating custom functions it is important to understand how variable accessibility is limited by the variable’s “scope”:
• Variables created outside a function have “global” scope, but are not normally accessible from within any function block
• Variables created inside a function have “local” scope so are only accessible from within that particular function block
As a variable created within a function is not accessible from elsewhere, its name may duplicate the name of a variable outside a function block, or within another function block, without conflict. This allows a global variable to contain a different value to a local variable of the same name.
Global variables in PHP are not like those in other programming languages such as C, where they are automatically available to functions. In PHP, global variables can only be used in functions if first explicitly declared inside the function block using the global keyword.
If you wish to use a global variable inside a function, you must first include a statement with the global keyword to declare that the variable name refers to a global variable, like this:
global variable-name ;
The scope of a variable created within a function can be altered to make it available globally by preceding its declaration with the global keyword – but this is bad practice and should be avoided.
Function statements can call other functions to execute their statements and can also call themselves to execute recursively. As with loops, a recursive function must alter the state of a tested condition so it will not continue forever. This might be a counter value that gets passed in as an argument from an initial function call, then gets incremented on successive recursive calls until it exceeds a value specified in a test. Alternatively, a static local variable could be declared to store an incrementing value like this:
static variable-name ;
Unlike other local variables, which lose their value when the program scope leaves the function, static variables retain their value. This means that the updated value of an incremented value stored in a static local variable is recognized on each function call.
A recursive function might otherwise reference a global variable counter value that gets incremented on successive recursive calls, until it exceeds a value specified in a test.
scope.php
Begin a PHP script by initializing a global variable with an integer and displaying the variable value
<?php
$number = 1 ; echo “Global number : $number <br>” ;
Next, define and call a function that initializes a like- named local variable and displays that variable value
function
show_local
()
{
$number = 100 ; echo “Local number : $number <hr>” ;
}
show_local () ;
Now, define and call a recursive function that increments the global variable and a static variable on each call
function recur ()
{
global $number ; static $letter = ‘A’ ;
if( $number < 14 )
{
echo “ $number : $letter | “ ;
$number ++ ; $letter ++ ; recur () ;
}
}
recur () ;
Finally, after the function block add a statement to display the modified global variable value
echo “<hr>Global number : $number ” ;
?>
Save the document in your web server’s
/htdocs
directory as
scope.php
then open the page via HTTP to see the global and local variable values
If you remove the static keyword from this function the $letter variable will simply contain ‘A’ each time the function is called.
PHP also has a special $GLOBALS array in which the value of a global variable can be referenced by its name. In this example you could alternatively use $GLOBALS[‘number’] to get the value.
Returning values
A custom PHP function can return a value to the caller by adding a statement using the return keyword, like this:
function function_name ( )
{
statement-to-be-executed ;
statement-to-be-executed ;
return value ;
}
The return statement is optional and if omitted, functions will return a NULL value to the caller by default.
Functions can only return a single item to the caller, so they cannot return multiple values. You can, however, assign multiple values to elements of an array and have a function return the single array to the caller, then unpack the values.
A return statement can include an expression to be evaluated so its single result will be returned to the caller. For example:
function square( int $number )
{
return $number * $number ;
}
echo square( 3 ) ; # Outputs 9
To ensure a function will only return a value of a desired data type, the function declaration can, optionally, specify the return type description such as int , float , string , bool or array , like this:
function function_name ( ) : int
{
statement-to-be-executed ;
statement-to-be-executed ;
return value ;
}
When a return data type is specified, a function that attempts to return an incorrect data type to the caller will result in an error.
The ability to specify a return data type is a new feature in PHP 7.
return.php
Begin a PHP script by defining a function that must only return an array of data
<?php
function supply () : array
{
// Statement to be inserted here.
}
Next, insert a statement to return an array of four mixed values
return array ( 75 , 3.142 , ‘Super PHP’ , True ) ;
After the function, add a statement that calls the function and assigns the returned array values to a variable
$array = supply () ;
Finally, add a loop to display each of the values returned from the function
foreach( $array as $data )
{
echo “Element Value : $data <br>” ;
}
?>
Save the document in your web server’s
/htdocs
directory as
return.php
then open the page via HTTP to see the returned values
In PHP the Boolean TRUE value is represented numerically as 1.
Calling back
PHP allows you to create “anonymous” functions that have no name specified in the function definition. Like other functions, these can accept arguments if parameters are specified and they can optionally return a value when called. Unlike other function definitions, which are code constructs, an anonymous function definition is an expression. This means that each anonymous function definition must be terminated by a semicolon, like this:
function ( )
{
statement-to-be-executed ;
statement-to-be-executed ;
return value ;
} ;
Don’t forget to add a terminating ; semicolon after each anonymous function definition.
On its own an anonymous function is of little use as, without a name, it cannot be called, but it can be useful in other ways:
• Assigned to a variable, an anonymous function can be called using the variable name
• Passed as a callable argument to another function, an anonymous function can be called later as a “callback”
• Returned from a function, an anonymous function retains access to the returning function’s variables in “closure”
By assigning an anonymous function to a variable you do, in effect, give the function a name and can call it and pass it arguments as you would any other function – using the variable name. Similarly, when you pass an anonymous function to another function it can be called back and passed arguments as you would any other function – using the parameter name. The PHP use keyword and & ampersand prefix allows an anonymous function to reference a local variable in the returning function.
callback.php
Begin a PHP script by assigning to a variable an anonymous function that accepts a single argument
<?php
$hello = function ( $user ) { echo “Hello $user !<br>” ; } ;
Next, add a statement that calls the anonymous function and passes a single argument
$hello ( ‘Mike’ ) ;
Now, define a regular function that accepts a single callable argument and calls that function passing a string
function greet ( callable $anon )
{
$anon ( ‘Carole Anne’ ) ;
}
Add a statement to call the function, defined in the previous step, passing the anonymous function that was assigned to a variable in the first step
greet( $hello ) ;
Next, define another regular function, which has one local variable and returns an anonymous function that references the local variable value
function meet () : callable
{
$time = ‘morning’ ;
return function( $name ) use( & $time )
{ return “Good $time , $name !” ; } ;
}
Assign to a variable the function defined in the previous step then call that function, passing a string argument
$meeting = meet () ;
echo $meeting ( ‘Susan’ ) ;
?>
Save the document in your web server’s
/htdocs
directory as
callback.php
then open the page via HTTP to see the returned values from anonymous functions
Remember to include the & ampersand prefix to create a reference to the variable value.
Notice that the final function call gets the ‘morning’ string from the parent scope.
Summary
• Custom functions allow PHP scripts to be modularized into sections of code that are easier to understand and maintain
• Function names must begin with a letter or underscore character and are not case-sensitive
• A function is defined by stating its name after the function keyword, then parentheses and braces containing statements
• A function accepting arguments is defined by including a comma-separated list of parameters within the parentheses
• Optionally, a function definition can specify the type of data to be passed from the caller by including a data type description before the parameter name
• Argument data is normally passed by value but can be passed by reference if the parameter name is given an & prefix
• Default argument values can optionally be specified in a function definition by assignment to the parameter name
• When a parameter name is given a ... splat operator prefix, multiple arguments can be passed to that parameter to create an array
• Variables created outside a function have global scope, but are not accessible from within a function block unless it includes a declaration using the global keyword
• Variables created inside a function have local scope so are only accessible from within that particular function block
• Local variables lose their value when the program scope leaves the function, but static variables retain their value
• The return keyword returns a single item to the caller and the function definition can optionally specify the return data type
• An anonymous function definition does not specify a name but is an expression so must end with a ; semicolon
• The use keyword and & ampersand prefix allow an anonymous function to reference a local variable in the returning function