Chapter_2_part8
Chapter_2_part8
Content
2.1. How to work with form data
2.2. How to code control statements
2.3. How to work with string and numbers
2.4. How to work with dates
2.5. How to work with arrays
2.6. How to work with cookie
2.7. How to work with session
2.8. How to work with functions
2.9. How to work with objects
2.10. How to work with regular expression, handle exception
C1, Slide 2
2.8. How to work with functions
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.
C13, Slide 3
2.8. How to work with functions
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.
C13, Slide 4
The syntax for a function
function function_name([$param_1,
$param_2, ... ,
$param_n]) {
// Code for function
[return [value];]
}
C13, Slide 5
A function with one parameter
function display_error($error) {
echo '<p class="error">' . $error . '</p>';
}
C13, Slide 6
A function call that doesn’t return a value
display_error('Value out of range.');
C13, Slide 7
Key terms
function
parameter
parameter list
return statement
argument
argument list
function call
calling a function
C13, Slide 8
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
C13, Slide 9
How to modify a string that’s passed by
reference
function wrap_in_tag(&$text, $tag) {
$before = '<' . $tag . '>';
$after = '</' . $tag . '>';
$text = $before . $text . $after;
}
C13, Slide 10
How to return multiple values
function array_analyze($array, &$sum, &$prod, &$avg) {
$sum = array_sum($array);
$prod = array_product($array);
$avg = $sum / count($array);
}
C13, Slide 11
A variable with global scope
$a = 10; // $a has global scope
function show_a() {
echo $a; // Inside function, $a is NULL
}
show_a(); // Displays nothing
C13, Slide 12
Another way to access a global variable
$c = 10; // $c has global scope
function show_c() {
$c = $GLOBALS['c']; // $c refers to global $c
echo $c;
}
show_c(); // Displays 10
C13, Slide 13
Key terms
scope
local scope
global scope
C13, Slide 14
A function with one default parameter
function get_rand_bool_text($type = 'coin') {
$rand = random_int(0, 1);
switch ($type) {
case 'coin':
$result = ($rand == 1) ? 'heads' : 'tails';
break;
case 'switch':
$result = ($rand == 1) ? 'on' : 'off';
break;
}
return $result;
}
C13, Slide 15
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;
}
C13, Slide 16
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;
}
C13, Slide 17
Calling a function with a default parameter
value
Omitting optional parameters
echo get_rand_bool_text();
echo display_error('Out of range');
$is_leap_year = is_leap_year();
C13, Slide 18
The syntax for type declarations
For the return type
function function_name(parameter_list) : return_type {}
C13, Slide 19
A function with one parameter type
declaration
function display_error(string $error) {
echo '<p class="error">' . $error . '</p>';
}
C13, Slide 20
Function calls without strict typing
display_error('Value out of range.');
// Displays 'Value out of range.'
display_error(1); // Displays '1'
C13, Slide 21
How to enable strict types mode
declare(strict_types=1); // must be first line of script
C13, Slide 22
Key terms
scalar value
type declarations
strict types mode
C13, Slide 23
Functions for working with
variable-length parameter lists
func_get_args()
func_num_args()
func_get_arg($i)
C13, Slide 24
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;
}
C13, Slide 25
Using required parameters
with a variable parameter list
function array_append(&$array, $x) {
$values = func_get_args(); // Also contains $array
array_shift($values); // Removes $array from front
foreach($values as $value) {
$array[] = $value;
}
}
C13, Slide 26
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;
}
C13, Slide 27
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;
}
}
}
C13, Slide 28
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;
}
?>
C13, Slide 29
Code that uses the library
// load the library
require_once('cart.php');
C13, Slide 30
Functions for working with the include path
get_include_path()
set_include_path($path)
C13, Slide 31
How to set the include path
Windows
set_include_path($include_path .
';C:\xampp\htdocs\book_apps\lib');
Mac OS X
set_include_path($include_path .
':/Applications/XAMPP/htdocs/book_apps/lib');
Linux
set_include_path($include_path .
':/opt/lampp/htdocs/book_apps/lib');
C13, Slide 32
How to create a namespace in a file
Using the statement syntax
<?php
namespace cart;
// Functions in cart namespace
?>
C13, Slide 33
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>';
}
}
?>
C13, Slide 34
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
C13, Slide 35
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
C13, Slide 36
Language constructs that can’t be use
in variable functions
die
eval
list
print
echo
include
require
unset
empty
include_once
require_once
exit
isset
return
C13, Slide 37
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.
You can’t use the language constructs listed above with variable
functions directly. However, you can use a wrapper function that
calls one of these constructs in a variable function.
C13, Slide 38
A function for sorting an array
with a custom comparison function
usort($array, $function)
C13, Slide 39
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;
};
C13, Slide 40
The spaceship operator
Operator Description
C13, Slide 41
An array of arrays
$employees = array (
array('name' => 'Ray', 'id' => 5685),
array('name' => 'Mike', 'id' => 4302),
array('name' => 'Anne', 'id' => 3674),
array('name' => 'Pren', 'id' => 1527),
array('name' => 'Joel', 'id' => 6256)
);
C13, Slide 42
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;
}
};
}
C13, Slide 43
Code that sorts the array by the name column
$sort_by_name = array_compare_factory('name');
usort($employees, $sort_by_name);
C13, Slide 44
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.
C13, Slide 45
The Add Item page
C13, Slide 46
The Cart page
C13, Slide 47
The cart.php file
<?php
namespace cart {
C13, Slide 48
The cart.php file (continued)
// Get a function for sorting the cart by 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;
}
};
}
C13, Slide 49
The index.php file
<?php
// Start session management
session_start();
C13, Slide 50
The index.php file (continued)
// Get the sort key
$sort_key = filter_input(INPUT_POST, 'sortkey');
if ($sort_key === NULL) { $sort_key = 'name'; }
C13, Slide 51
The index.php file (continued)
// Add or update cart as needed
switch($action) {
case 'add':
$key = filter_input(INPUT_POST, 'productkey');
$quantity = filter_input(INPUT_POST, 'itemqty');
cart\add_item($key, $quantity);
include('cart_view.php');
break;
case 'update':
$new_qty_list = filter_input(INPUT_POST, 'newqty',
FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
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;
C13, Slide 52
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;
}
?>
C13, Slide 53
The cart_view.php file
<!DOCTYPE html>
<html>
<head>
<title>My Guitar Shop</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<header>
<h1>My Guitar Shop</h1>
</header>
<main>
<h1>Your Cart</h1>
<?php if (empty($_SESSION['cart13']) ||
count($_SESSION['cart13']) == 0) : ?>
<p>There are no items in your cart.</p>
<?php else: ?>
C13, Slide 54
The cart_view.php file
<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
<?php endif; ?>
name="sortkey" value="name"></th>
<th class="right">
<input type="radio"
<?php if ($sort_key == 'cost') : ?>
checked
<?php endif; ?>
name="sortkey" value="cost">
Item Cost</th>
C13, Slide 55
The cart_view.php file (continued)
<th class="right" >
<input type="radio"
<?php if ($sort_key == 'qty') : ?>
checked
<?php endif; ?>
name="sortkey" value="qty">
Quantity</th>
<th class="right">
<input type="radio"
<?php if ($sort_key == 'total') : ?>
checked
<?php endif; ?>
name="sortkey" value="total">
Item Total</th>
</tr>
<?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>
C13, Slide 56
The cart_view.php file (continued)
<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>
<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">
</td>
</tr>
C13, Slide 57
The cart_view.php file
</table>
<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>
</main>
</body>
</html>
C13, Slide 58