PHP Function Tutorial
This page is a small tutorial on how to use the PHP Functions. It’s not meant as a sole repository for learning how to write PHP 5.0 forward functions but covers their principal features. It also presumes that you’ve read or understand the material in the Basic PHP Tutorial.
Function Definition ↓
This sections describes the structure of PHP functions.
PHP functions support two paradigms. They’re pass-by-value and pass-by-reference functions. Both support the behavior of functions and procedures.
When functions have a return
value they act as functions. Functions are stand alone processing units. When functions don’t have a return
value they act like procedures. Procedures work inside the processing scope of scripts or other functions.
- Pass-by-value
- Functions take a copy of values (known as call parameters) and use them to perform processing, and after processing the values they return a value. The value can be a result that acknowledges successful or failed processing of the function, or a value produced by the function.
- Procedures take a copy of values (known as call parameters) and use them to perform processing, however, they return no acknowledgment of whether or not the process completed successfully.
- Pass-by-reference
- Functions take references (also known as pointers) to variables as call parameters. They use the references to access and potentially change the calling variables, and they return a value that you can assign to another variable or evaluate in an
if
-statement. The return value may be an acknowledgment of successful or failed processing, or a calculated value. At the conclusion of this type of function, the variables passed by reference may have a new value, data type, or both. - Procedures take references (also known as pointers) to variables as call parameters. They also use the references to access and potentially change calling variables but they return no value that can be assigned or evaluated after processing. Like the pass-by-reference function, any variable passed by reference may have a new value, data type, or both.
The function prototypes for PHP are:
- Any function that fails to return a value that can serve as an expression or right operand acts like a procedure. They have the following prototype:
<?php void function foo() { statement; } ?> |
- Any function that returns a value that can serve as an expression or right operand acts like a function. The mixed notation represents any supported data type of the programming language, like
int
,double
,float
, orstring
.
They have the following prototype:
<?php mixed function foo() { statement; } ?> |
Functions are in scope when they’re read into scope. In PHP, that only happens when they’re not nested in another function. Likewise, dynamic functions aren’t placed in scope until they’re called. Dynamic functions are also unavailable outside of the containing function unless you assign them to script-level variables (covered later in this tutorial).
Creating & Using Functions ↓
This sections shows you how to create and use functions in an HTML page.
Pass-by-value Function ↓
This sections shows you how to create and use pass-by-value functions in an HTML page.
This type of function can serve multiple uses. You’ll examine a few ways to use this type of function in the examples.
Function
This example prints a bold statement as a paragraph to a web page by calling a function and printing the return value (or expression).
1 2 3 4 5 6 7 8 9 10 11 | <?php // Call a local function. print bold_text("Hello Bold New World!"); // Define a parameter driven function that returns nothing, therefore // a function that acts like a procedure. function bold_text($formal_parameter) { // Return the formatted string. return "<p><b>$formal_parameter</b></p>"; } ?> |
This example also prints a bold statement as a paragraph to a web page. The difference is that it uses the return value as an expression in an if
-statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php // Define a local variable. $a = bold_text("Hello Bold New World!"); // Validate a not null string and print it. if ($a) { print $a; } // Define a parameter driven function that returns nothing, therefore // a function that acts like a procedure. function bold_text($formal_parameter) { // Return the formatted string. return "<p><b>$formal_parameter</b></p>"; } ?> |
Procedure
Like the others, this example prints a bold statement as a paragraph to a web page. It does it as a procedure because the print statement is inside the function and there is no return statement. As discussed, the absence of a return statement makes this behave like a procedure. You should note that the double quotes let us embed a variable reference inside the expression.
1 2 3 4 5 6 7 8 9 10 11 | <?php // Call a local function. print_bold("Hello Bold New World!"); // Define a parameter driven function that returns nothing, therefore // a function that acts like a procedure. function print_bold($formal_parameter) { // Print the formatted string. print "<p><b>$formal_parameter</b></p>"; } ?> |
If you replace the double quotes with single quotes, the variable name would print, as $formal_parameter
. When you want to use single quotes because you’ve got double quotes inside a string, you use the following approach.
1 2 3 4 5 6 7 8 9 10 11 | <?php // Call a local function. print_bold("Hello Bold New World!"); // Define a parameter driven function that returns nothing, therefore // a function that acts like a procedure. function print_bold($formal_parameter) { // Print the formatted string. print '<p><b>'.$formal_parameter.'</b></p>'; } ?> |
Pass-by-reference Function ↓
This sections shows you how to create and use pass-by-reference functions in an HTML page.
This type of function can serve multiple uses. You’ll examine a few ways to use this type of function in the examples.
Function
This example assigns a statement to a script-level variable. Then, it passes the variable by reference to the bold_text()
function. The function takes the variable and pads XHTML before and after the contents and assigns it back to itself. If the assignment works, it returns a Boolean true.
When the calling script prints the variable after the function call, it has the XHTML added inside the function. This demonstrates a pass-by-reference function because it also returns a Boolean value as an expression.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php // Declare a string message variable. $msg = "Hello Bold New World!"; // Call a local function. if (bold_text($msg)) { print $msg; } else { print "<p>The function failed ... </p>"; } // Define a parameter driven function that returns a Boolean. function bold_text(&$formal_parameter) { // Assign the formatted value to the input parameter. $formal_parameter = "<p><b>$formal_parameter</b></p>"; // Return Boolean true. return true; } ?> |
Procedure
Like preceding function, this example uses a pass-by-reference architecture. It dispenses with validating the performance of the function and simply prints the modified variable after a function call.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php // Declare a string message variable. $msg = "Hello Bold New World!"; // Call a local function. bold_text($msg); // Print the modified contents of the variable. print $msg; // Define a parameter driven function that returns nothing, therefore // a function that acts like a procedure. function bold_text(&$formal_parameter) { // Assign the formatted value to the input parameter. $formal_parameter = "<p><b>$formal_parameter</b></p>"; } ?> |
Dynamic Function ↓
This sections shows you how to create and use dynamic functions in an HTML page.
This type of function can serve multiple uses. The most important is that it is never placed in your function namespace, which means it’s behavior can change at run-time. You’ll examine a two ways to use this type of function in the examples.
Function
A word of caution with this example. It’s a bit unnecessary in this scope but it’s simple enough to highlight the behavior of dynamic functions.
This example creates variables that hold XHTML formatting parameters. The format_text()
function adds formatting to the front and end of a string through a dynamic function. Writing this as a function lets you call it repeatedly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <?php // Declare formatting variables. $bold = "b"; $italic = "i"; $para = "p"; // Declare a string message variable. $msg = "Hello Bold New World!"; /* Call a local function with nested calls to the same function. The most nested call runs first, the one around it second and the external one last. Each call adds some feature to the string. */ print format_text(format_text(format_text($msg,$bold),$italic),$para); // Print the modified contents of the variable. print $msg; /* Define a dynamic parameter driven function that returns nothing, therefore a function that acts like a procedure. In this case pass the first parameter by reference and the second by value. */ function format_text($formal_text,$format_code) { /* Create a dynamic function that will never become part of your function name space. This technique lets you define a polymorphic function without using an Object. */ $dynamic = create_function('$formal_text,$format_code','return "<".$format_code.">".$formal_text."</".$format_code.">";'); // Assign the dynamically formatted value to the input parameter. return $dynamic($formal_text,$format_code); } ?> |
Naturally, it would be simpler to write this particular function like this:
1 2 3 | // Function to add XHTML formatting codes. function format_text($formal_text,$format_code) { return "<".$format_code.">".$formal_text."</".$format_code.">"; } |
Procedure
Like the preceding function, this example uses a mixture of pass-by-reference and pass-by-value architectures. It defines a nested dynamic function that lets you apply different formatting commands.
You should note that this type of solution is less effective than the use of a function acting like a function above. However, it’s purpose is to simply illustrate potential uses of dynamic functions that act like procedures.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <?php // Declare formatting variables. $bold = "b"; $italic = "i"; $para = "p"; // Declare a string message variable. $msg = "Hello Bold New World!"; // Call a local function that works like a procedure. format_text($msg,$bold); format_text($msg,$italic); format_text($msg,$para); // Print the modified contents of the variable. print $msg; /* Define a dynamic parameter driven function that returns nothing, therefore a function that acts like a procedure. In this case pass the first parameter by reference and the second by value. */ function format_text(&$formal_text,$format_code) { /* Create a dynamic function that will never become part of your function name space. This technique lets you define a polymorphic function without using an Object. */ $dynamic = create_function('$formal_text,$format_code','return "<".$format_code.">".$formal_text."</".$format_code.">";'); // Assign the dynamically formatted value to the input parameter. $formal_text = $dynamic($formal_text,$format_code); } ?> |
Function Default Parameters ↓
This sections describes how to use default parameter values in functions.
You can define functions with mandatory or optional parameters. You can only use optional parameters in pass-by-value functions. Mandatory parameters precede optional parameters in the formal parameter list.
A mandatory parameter requires that any call to the function provide a value or variable reference. Pass-by-value functions take a value or expression (return value from another function), while pass-by-reference functions require a variable.
An optional parameter requires a value. The value can be any scalar data type, literal value, or a null value. The following example calls the add()
function with two variables, and then one variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php // Declare a couple integer variables. $a = 2; $b = 2; // Call a local function. print "<p>The sum of [\$a] and [\$b] is [".add($a,$b)."]</p>"; print "<p>The sum of [\$a] and [default] is [".add($a)."]</p>"; // Define a parameter driven function that returns nothing, therefore // a function that acts like a procedure. function add($one,$two = 0) { return $one + $two; } ?> |
The following results are printed to a web page for rendering:
<p>The sum of [$a] and [$b] is [4]</p> <p>The sum of [$a] and [default] is [2]</p> |
Variable-length Parameter Lists ↓
This sections describes how to create functions without parameter lists.
You can define functions without formal parameter lists even when you plan to process call parameters. This technique is called variable-length parameter lists or flexible parameter passing.
The PHP programming language provides three functions that make this possible. They’re listed in the following table.
Logical Operators | |
---|---|
Function | Description |
func_get_arg() | The function takes one formal parameter, which is the numeric index in the array of parameter values. It returns the value pointed to by the index. If a numeric value is provided and not found in the list, a null is returned. |
func_get_args() | The function has no formal parameter. It returns the array of calling parameters indexed by numbers starting with zero. If there are no calling parameters, it returns an empty array. A subsequent call to the func_get_arg() function returns an out-of-bounds error. |
func_num_args() | The function has no formal parameter. It returns the number of calling parameters. If there aren’t any calling parameters, it returns a zero. |
The following shows you a function acting like a procedure. Simply because it’s easier to print a series of messages to a web page.
While the format_strings()
function has an empty formal parameter list, the function call passes two parameters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php // Call function. format_strings("Oh yeah, baby!","There's no prototype (parameter list) required."); // Define a function that uses a variable-length parameter list. function format_strings() { // Check for actual parameters. if (func_num_args() > 0) { // Process the parameters in a loop. for ($i = 0; $i < func_num_args(); $i++) { print "<p>".func_get_arg($i)."</p>"; } } else { // Do nothing because there aren't any parameters. null; } } ?> |
The following results are printed to a web page for rendering:
<p>Oh yeah, baby!</p> <p>There's no prototype (parameter list) required.</p> |
Great tutorial!
Martin Quito
16 Aug 14 at 10:00 pm