Alternate Way to Write PHP Function Arguments Part 2: Using Associative Arrays
The standard process for building user-defined functions is to manually list out the arguments. The problem with this method is that the arguments need to appear in the order given. If the function has several optional arguments, you need to pass a value for all arguments just to specify the last one. Well, let's look at an alternate way to write functions which provides more freedom.
Background
In the previous post (Alternate Way to Write PHP Function Arguments Part 1: The Standard Process), we built a function that displays / returns a list of staff members based on the arguments used. Here is the final code:
<?php
//CONNECT WITH DATABASE
require "{$_SERVER['DOCUMENT_ROOT']}/../database_connection.php";
$connect = new connect();
$mysqli = $connect->databaseObject;
//FUNCTION DISPLAYS/GETS THE INDICATED STAFF MEMBERS
function getStaff($mysqli, $types=array(), $specificIDs=array(), $display=true) {
//PREPARE THE WHERE CLAUSE
$whereClause = '';
$whereOptions = array();
if(!empty($types)) { $whereOptions[] = "type in ('" . implode("', '", $types) . "')"; }
if(!empty($specificIDs)) { $whereOptions[] = "id in ('" . implode("', '", $specificIDs) . "')"; }
if(!empty($whereOptions)) { $whereClause = "WHERE " . implode(' AND ', $whereOptions); }
//GET STAFF MEMBERS
$staffMembers = array();
$sql = "SELECT firstName, lastName FROM staffList $whereClause ORDER BY lastName, firstName";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
$staffMembers[] = $row;
}
//IF DISPLAYING THE STAFF MEMBERS
if($display) {
print '<ul>';
foreach($staffMembers as $currMember) {
print "<li>{$currMember['firstName']} {$currMember['lastName']}</li>";
}
print '</ul>';
//ELSE...RETURN ARRAY
} else {
return $staffMembers;
}
}
?>
In the previous post, you may have noticed that some of the function calls were a bit cumbersome. To have the function return the staff member information, for example, the middle two arguments are included even though we're just passing what would normally be the default values.
<?php
$staffMembers = getStaff($mysqli, array(), array(), false);
?>
Alternate Solution
Instead of hard-coding the individual arguments, a single argument could be created which will be used to pass an associative array.
<?php
//FUNCTION DISPLAYS/GETS THE INDICATED STAFF MEMBERS
function getStaff($argumentsArray=array()) {
//...
}
?>
The overall function needs to be modified to use the new associative array. Instead of $mysqli, for example, we will use $argumentsArray['mysqli']. Let's also make sure that the function displays the staff information be default.
<?php
//CONNECT WITH DATABASE
require "{$_SERVER['DOCUMENT_ROOT']}/../database_connection.php";
$connect = new connect();
$mysqli = $connect->databaseObject;
//FUNCTION DISPLAYS/GETS THE INDICATED STAFF MEMBERS
function getStaff($argumentsArray=array()) {
//IF NOT PASSED, SET DEFAULT FOR THE "display" ARGUMENT
if(!isset($argumentsArray['display'])) {
$argumentsArray['display'] = true;
}
//PREPARE THE WHERE CLAUSE
$whereClause = '';
$whereOptions = array();
if(!empty($argumentsArray['types'])) { $whereOptions[] = "type in ('" . implode("', '", $argumentsArray['types']) . "')"; }
if(!empty($argumentsArray['specificIDs'])) { $whereOptions[] = "id in ('" . implode("', '", $argumentsArray['specificIDs']) . "')"; }
if(!empty($whereOptions)) { $whereClause = "WHERE " . implode(' AND ', $whereOptions); }
//GET STAFF MEMBERS
$staffMembers = array();
$sql = "SELECT firstName, lastName FROM staffList $whereClause ORDER BY lastName, firstName";
$result = $argumentsArray['mysqli']->query($sql);
while($row = $result->fetch_assoc()) {
$staffMembers[] = $row;
}
//IF DISPLAYING THE STAFF MEMBERS
if($argumentsArray['display']) {
print '<ul>';
foreach($staffMembers as $currMember) {
print "<li>{$currMember['firstName']} {$currMember['lastName']}</li>";
}
print '</ul>';
//ELSE...RETURN ARRAY
} else {
return $staffMembers;
}
}
?>
Calling the Function
The function calls now only need to include the necessary arguments. To have the function return the staff information so we can customize how the names are displayed, call the function as follows:
<?php
$staffMembers = getStaff(array(
'mysqli' => $mysqli,
'display' => false
));
print '<ul>';
foreach($staffMembers as $currMember) {
print "<li>{$currMember['lastName']}, {$currMember['firstName']}</li>";
}
print '</ul>';
?>
Conclusion
Passing function arguments as an associative array allows us to call functions without needing to include any unnecessary arguments. Using the array also makes it so the order of the arguments no longer matters. Since the order doesn't matter, it's also easier to incorporate new arguments down the road.
0 Comments
There are currently no comments.
Leave a Comment