Alternate Way to Write PHP Function Arguments Part 1: The Standard Process
When calling user-defined functions, there are occasions where it feels like optional arguments become required. I've seen third-party solutions like WordPress find a way to get around this issue. But it wasn't until recently that I've attempted my own solution. Before getting into an alternate method of passing function arguments, however, let's look at the standard process.
Database Information
For the example below, we'll use a database table called "staffList" which contains the following information:
id | updated | firstName | lastName | type |
---|---|---|---|---|
1 | 2013-07-01 | John | Smith | Support |
2 | 2013-05-06 | Jack | Jones | Researcher |
3 | 2013-06-18 | Jake | Bible | Researcher |
4 | 2013-07-17 | Steve | Stevenson | Support |
5 | 2013-04-08 | Bill | Smith | Researcher |
6 | 2013-08-20 | Arnold | Schwarzenegger | Admin |
7 | 2013-08-22 | Jambi | Paragon | Researcher |
Example Function
Since we're querying a database, a connection needs to be established. Note that more information about the connection script used for this example can be found in an earlier post titled "End PHP Scripts Gracefully After a Failed Database Connection."
<?php
//CONNECT WITH DATABASE
require "{$_SERVER['DOCUMENT_ROOT']}/../database_connection.php";
$connect = new connect();
$mysqli = $connect->databaseObject;
?>
Next we'll define the function and arguments.
<?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) {
//...
}
?>
As you may have noticed, the function has one required argument ($mysqli) and three optional arguments ($types, $specificIDs, and $display). We'll get into what each of these arguments do shortly. For now, let's add the basic query for getting the staff member information.
<?php
//...
//FUNCTION DISPLAYS/GETS THE INDICATED STAFF MEMBERS
function getStaff($mysqli, $types=array(), $specificIDs=array(), $display=true) {
//GET STAFF MEMBERS
$staffMembers = array();
$sql = "SELECT firstName, lastName FROM staffList ORDER BY lastName, firstName";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
$staffMembers[] = $row;
}
}
?>
With the query results assigned to the $staffMembers array, the function's default action is to display them as an unordered list.
<?php
//...
//FUNCTION DISPLAYS/GETS THE INDICATED STAFF MEMBERS
function getStaff($mysqli, $types=array(), $specificIDs=array(), $display=true) {
//GET STAFF MEMBERS
$staffMembers = array();
$sql = "SELECT firstName, lastName FROM staffList 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>';
}
}
?>
However, let's add an option for returning the results as an array.
<?php
//...
//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;
}
}
?>
All that's left to do now, besides calling the function, is to utilize the $types and $specificIDs arguments. Both of these arguments will be used to limit the number of results returned by the query. So let's use them to build a WHERE clause.
<?php
//...
//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 ORDER BY lastName, firstName";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
$staffMembers[] = $row;
}
//...
}
?>
The WHERE clause can then be added to the query.
<?php
//...
//FUNCTION DISPLAYS/GETS THE INDICATED STAFF MEMBERS
function getStaff($mysqli, $types=array(), $specificIDs=array(), $display=true) {
//...
//GET STAFF MEMBERS
$staffMembers = array();
$sql = "SELECT firstName, lastName FROM staffList $whereClause ORDER BY lastName, firstName";
//...
}
?>
Final Code
To help give you a better sense on how the pieces fit together, here is the entire script. Note that a basic function call is included at the end.
<?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;
}
}
//CALL THE FUNCTION
getStaff($mysqli);
?>
Calling the Function
The basic function call (shown in the Final Code section above) pulls all staff members from the database and displays them as an unordered list.
- Jake Bible
- Jack Jones
- Jambi Paragon
- Arnold Schwarzenegger
- Bill Smith
- John Smith
- Steve Stevenson
If we only wanted to display "Support" staff members, the call would be modified to
getStaff($mysqli, array('support'));
To display a specific staff member's name, we can specify their ID:
getStaff($mysqli, array(), array(3));
In some cases, we may want the ability to do more with the staff information. Perhaps the names need to be listed with the last name first. We just need to update the $display flag so that the function returns an array.
<?php
$staffMembers = getStaff($mysqli, array(), array(), false);
print '<ul>';
foreach($staffMembers as $currMember) {
print "<li>{$currMember['lastName']}, {$currMember['firstName']}</li>";
}
print '</ul>';
?>
Conclusion
As you can see, the function is fairly flexible. The problem with the function is that some of the "optional" arguments become "required." When asking the function to return an array, for example, a value needs to be specified for both $types and $specificIDs. In the next post, we'll look at a solution that only requires us to specify the arguments when we want to use something other than the default.
0 Comments
There are currently no comments.
Leave a Comment