Chapter 13
Chapter 13
How to create
and use functions
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 1
Objectives
Applied
1. Create any of the functions that your applications require. These
functions may need to pass arguments by value or reference,
provide default values for arguments, or provide for a variable
number of arguments.
2. Call any of the functions that your applications require.
3. Create and use function libraries and namespaces.
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 2
Objectives (continued)
Knowledge
1. Describe the creation and use of functions.
2. Distinguish between passing an argument by value and passing an
argument by reference.
3. Describe local scope and global scope as it applies to the variables
within functions, and describe the scope of functions themselves.
4. Describe the use of function libraries and namespaces.
Terms
function argument
parameter argument list
parameter list function call
return statement calling a function
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 3
The syntax for a function
function function_name([$param_1,
$param_2, ... ,
$param_n]) {
// Code for function
[return [value];]
}
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 4
A function with one parameter
function display_error($error) {
echo '<p class="error">' . $error . '</p>';
}
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 5
An argument passed by value
function add_3_by_val($value) {
$value += 3;
echo '<p>Number: ' . $value . '</p>';
}
$number = 5;
add_3_by_val($number); // Displays 8
echo '<p>Number: ' . $number . '</p>'; // Displays 5
$number = 5;
add_3_by_ref($number); // Displays 8
echo '<p>Number: ' . $number . '</p>'; // Displays 8
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 6
How to modify a string that’s passed by reference:
function wrap_in_tag(&$text, $tag) {
$before = '<' . $tag . '>';
$after = '</' . $tag . '>';
$text = $before . $text . $after;
}
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 7
How to return multiple values
function array_analyze($array, &$sum, &$prod, &$avg) {
$sum = array_sum($array);
$prod = array_product($array);
$avg = $sum / count($array);
}
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 8
By default, functions do not have
access to global variables
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 9
To access several global variables, use the
predefined $GLOBALS array
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 10
When a default value is provided for a parameter,
that parameter becomes optional.
A function with one default parameter
function get_rand_bool_text($type = 'coin') {
$rand = mt_rand(0, 1);
switch ($type) {
case 'coin':
$result = ($rand == 1) ? 'heads' : 'tails';
break;
case 'switch':
$result = ($rand == 1) ? 'on' : 'off';
break;
}
return $result;
}
echo get_rand_bool_text('switch');
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 11
Default parameter values must be scalar
values, arrays of scalar values, or NULL
A function with an optional parameter
function is_leap_year($date = NULL) {
if (!isset($date)) {
$date = new DateTime();
}
if ($date->format('L') == '1') return true;
else return false;
}
$is_leap_year = is_leap_year();
$is_leap_year =
is_leap_year(new DateTime('March 15, 2015'));
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 12
A function with one required and two default
parameters
function display_error($error,
$tag = 'p',
$class = 'error') {
$opentag = '<' . $tag . ' class="' . $class . '">';
$closetag = '</' . $tag . '>';
echo $opentag . $error . $closetag;
}
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 13
Functions for working
with variable-length parameter lists
func_get_args() /*returns an array containing the
arguments passed to the function.*/
func_num_args()
func_get_arg($i)
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 14
A function that averages one or more numbers
function average($x) { // $x forces one argument
$count = func_num_args();
$total = 0;
for($i = 0; $i < $count; $i++) {
$total += func_get_arg($i);
}
return $total / $count;
}
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 15
A library of functions (the cart.php file)
<?php
// Add an item to the cart
function cart_add_item(&$cart, $name, $cost,
$quantity) {
$total = $cost * $quantity;
$item = array(
'name' => $name,
'cost' => $cost,
'qty' => $quantity,
'total' => $total
);
$cart[] = $item;
}
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 16
A library of functions (the cart.php file) (cont.)
// Update an item in the cart
function cart_update_item(&$cart, $key, $quantity) {
if (isset($cart[$key])) {
if ($quantity <= 0) {
unset($cart[$key]);
} else {
$cart[$key]['qty'] = $quantity;
$total = $cart[$key]['cost'] *
$cart[$key]['qty'];
$cart[$key]['total'] = $total;
}
}
}
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 17
A library of functions (the cart.php file) (cont.)
// Get cart subtotal
function cart_get_subtotal($cart) {
$subtotal = 0;
foreach ($cart as $item) {
$subtotal += $item['total'];
}
$subtotal = round($subtotal, 2);
$subtotal = number_format($subtotal, 2);
return $subtotal;
}
?>
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 18
Code that uses the library
// load the library
require_once('cart.php');
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 19
Functions for working with the include path
get_include_path()
set_include_path($path)
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 20
How to set the include path
Windows
set_include_path($include_path .
';C:\xampp\htdocs\book_apps\lib');
Mac or Linux
set_include_path($include_path .
':/Applications/XAMPP/htdocs/book_apps/lib');
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 21
Function scope in PHP
cart_add_item(…)
cart_update_item(…)
cart_get_subtotal(…)
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 23
How to create a namespace in a file
Using the statement syntax
<?php
namespace cart;
// Functions in cart namespace
?>
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 24
How to use the functions in a namespace
Create a file that contains a namespace with one function
<?php
namespace murach\errors {
function log($error) {
echo '<p class="error">' . $error . '</p>';
}
}
?>
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 25
Variable Functions
A variable function
$function = (mt_rand(0,1) == 1) ?
'array_sum' : 'array_product';
$values = array(4, 9, 16);
$result = $function($values); /* 29 for array_sum,
576 for array_product */
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 26
How variable functions and callbacks work
A variable function is a function name stored in a variable as a
string. When PHP encounters a variable function, it evaluates the
variable and attempts to call the function.
To call a variable function, code the variable name followed by a
set of parentheses. Within the parentheses, code the argument list
for the function.
You can use a variable function when the function isn’t known
until runtime.
You can use a variable function in a function that uses a callback.
A callback is a function that’s passed as an argument to another
function.
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 27
A function that uses a callback
function validate($data, $functions) {
$valid = true;
foreach ($functions as $function) {
$valid = $valid && $function($data);
}
return $valid;
}
function is_at_least_18($number) {
return $number >= 18;
}
function is_less_than_62($number) {
return $number < 62;
}
$age = 25;
$functions = array(
'is_numeric', 'is_at_least_18', 'is_less_than_62');
$is_valid_age = validate($age, $functions); // TRUE
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 28
Language constructs that can’t be used in variable
functions
die
eval
list
print
echo
include
require
unset
empty
include_once
require_once
exit
isset
return
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 29
A function for sorting an array
with a custom comparison function
usort($array, $function)
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 30
How to create and use an anonymous function
A custom sorting function
$compare_function = function ($left, $right) {
$l = (float) $left;
$r = (float) $right;
if ($l < $r) return -1;
if ($l > $r) return 1;
return 0;
};
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 32
A function to sort the array by any column
function array_compare_factory($sort_key) {
return function ($left, $right) use ($sort_key) {
if ($left[$sort_key] < $right[$sort_key]) {
return -1;
} else if ($left[$sort_key] >
$right[$sort_key]) {
return 1;
} else {
return 0;
}
};
}
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 33
How closures work
A closure is an inner function that has access to the outer
function’s variables. To create a closure, code a use clause in the
inner function.
To allow the inner function to change the outer function’s variable,
use the reference operator (&) in the use clause.
The outer function’s variables are available after it has finished
executing as long as there is a reference to the inner function.
The inner function is an anonymous function that is returned by the
outer function or stored in a parameter that was passed by
reference. You can store it in a variable and call it as a variable
function like you would an anonymous function.
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 34
The Add Item page
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 35
The Cart page
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 36
The cart.php file
<?php
namespace cart {
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 37
The cart.php file (continued)
// Get a function for sorting the cart on the specified key
function compare_factory($sort_key) {
return function($left, $right) use ($sort_key) {
if ($left[$sort_key] == $right[$sort_key]) {
return 0;
} else if ($left[$sort_key] <
$right[$sort_key]) {
return -1;
} else {
return 1;
}
};
}
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 38
The index.php file
<?php
// Start session management
session_start();
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 39
The index.php file (continued)
// Get the sort key
if (isset($_POST['sortkey'])) {
$sort_key = $_POST['sortkey'];
} else {
$sort_key = 'name';
}
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 40
The index.php file (continued)
// Add or update cart as needed
switch($action) {
case 'add':
cart\add_item($_POST['productkey'],
$_POST['itemqty']);
include('cart_view.php');
break;
case 'update':
$new_qty_list = $_POST['newqty'];
foreach($new_qty_list as $key => $qty) {
if ($_SESSION['cart13'][$key]['qty'] != $qty) {
cart\update_item($key, $qty);
}
}
cart\sort($sort_key);
include('cart_view.php');
break;
case 'show_cart':
cart\sort($sort_key);
include('cart_view.php');
break;
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 41
The index.php file (continued)
case 'show_add_item':
include('add_item_view.php');
break;
case 'empty_cart':
unset($_SESSION['cart13']);
include('cart_view.php');
break;
}
?>
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 42
The cart_view.php file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Guitar Shop</title>
<link rel="stylesheet" type="text/css" href="main.css"/>
</head>
<body>
<div id="page">
<div id="header">
<h1>My Guitar Shop</h1>
</div>
<div id="main">
<h1>Your Cart</h1>
<?php if (count($_SESSION['cart13']) == 0) : ?>
<p>There are no items in your cart.</p>
<?php else: ?>
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 43
The cart_view.php file (continued)
<form action="." method="post">
<input type="hidden" name="action"
value="update"/>
<table>
<tr id="cart_header">
<th class="left">
Item <input type="radio"
<?php if ($sort_key == 'name') : ?>
checked="checked"
<?php endif; ?>
name="sortkey" value="name"/></th>
<th class="right">
<input type="radio"
<?php if ($sort_key == 'cost') : ?>
checked="checked"
<?php endif; ?>
name="sortkey" value="cost"/>
Item Cost</th>
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 44
The cart_view.php file (continued)
<th class="right" >
<input type="radio"
<?php if ($sort_key == 'qty') : ?>
checked="checked"
<?php endif; ?>
name="sortkey" value="qty"/>
Quantity</th>
<th class="right">
<input type="radio"
<?php if ($sort_key == 'total') : ?>
checked="checked"
<?php endif; ?>
name="sortkey" value="total"/>
Item Total</th>
</tr>
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 45
The cart_view.php file (continued)
<?php foreach( $_SESSION['cart13']
as $key => $item ) :
$cost =
number_format($item['cost'], 2);
$total =
number_format($item['total'], 2);
?>
<tr>
<td>
<?php echo $item['name']; ?>
</td>
<td class="right">
$<?php echo $cost; ?>
</td>
<td class="right">
<input type="text" class="cart_qty"
name=
"newqty[<?php echo $key; ?>]"
value=
"<?php echo $item['qty']; ?>"/>
</td>
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 46
The cart_view.php file (continued)
<td class="right">
$<?php echo $total; ?>
</td>
</tr>
<?php endforeach; ?>
<tr id="cart_footer">
<td colspan="3"><b>Subtotal</b></td>
<td>$<?php echo cart\get_subtotal(); ?>
</td>
</tr>
<tr>
<td colspan="4" class="right">
<input type="submit"
value="Update Cart"
id="update_button" />
</td>
</tr>
</table>
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 47
The cart_view.php file (continued)
<p>Click "Update Cart" to update quantities
or the sort sequence
in your cart.<br />Enter a quantity of 0 to
remove an item.
</p>
</form>
<?php endif; ?>
<p><a href=".?action=show_add_item">Add Item</a></p>
<p><a href=".?action=empty_cart">Empty Cart</a></p>
Murach's PHP and MySQL, C13 © 2010, Mike Murach & Associates, Inc. Slide 48