Computer programming exists in order to automate tasks either too difficult or tedious for humans, from mortgage payment calculation to calculating the trajectory of a football launched by a virtual player in a video game You’ll often find that such tasks are comprised of bits of logic that can be reused elsewhere, not only within the same application but also in many other applications. For example, an e-commerce application might need to validate an e-mail address on several different pages, such as when a new user registers to use a website, when somebody wants to add a product review, or when a visitor signs up for a newsletter. The logic used to validate an e-mail address is surprisingly complex, and therefore it would be ideal to maintain the code in a single location rather than embed it into numerous pages.
Thankfully, the concept of embodying these repetitive processes within a named section of code and then invoking this name when necessary has long been a key feature of modern computer languages. Such a section of code is known as a function , and it grants you the convenience of a singular point of reference if the process it defines requires changes in the future, which greatly reduces both the possibility of programming errors and maintenance overhead. Fortunately, the PHP language comes with more than 1,000 native functions, but it’s also easy to create your own! In this chapter, you’ll learn all about PHP functions, including how to create and invoke them, pass input to them, use type hinting , return both single and multiple values to the caller, and create and include function libraries.
Invoking a Function
Try It
PHP’s library of functions is simply massive, and as a result you’re going to spend quite a bit of time reading the documentation in order to learn more about a particular function’s input parameters and behavior. This is particularly true when you want to use a function such as date(), which supports almost 40 different specifiers for defining how a date should be formatted. Fortunately, the official PHP site offers a convenient shortcut useful for quickly accessing a function by name; just append the function name onto the domain https://www.php.net . Therefore, to access the date() function, navigate to https://www.php.net/date .
Admittedly, the date() function is somewhat of an anomaly given the sheer number of format specifiers; most PHP functions accept two or three parameters and that’s it. Even so, chances are you’ll find the ability to quickly navigate to a function to be incredibly handy. Incidentally, it even works for partial function names! For instance, suppose you want to convert a string to all uppercase, but don’t remember the specific function name, only recalling that the name included the string “upper.” Head over to https://www.php.net/upper and you’ll be presented with a list of relevant functions and other documentation entries!
Most modern IDEs like PHP Storm, Sublime Text, Eclipse, etc., provide an autocomplete feature that will show the argument list for any function. This applies to both built-in PHP functions and to functions you write or include from libraries. You don’t have to keep reading the PHP manual every time you want to check the order of arguments, but if you are hunting for functions it’s a handy tool.
Creating a Function
While PHP does not impose many restrictions on the function name (provided it does not clash with an existing PHP function) nor formatting convention, a commonly used formatting standard is the camel case format ( https://en.wikipedia.org/wiki/CamelCase ), which dictates that the first letter of the function name is lowercase and the first letter of any subsequent compound words are capitalized. Also, you should use descriptive names in order to encourage code readability!
When the function executes, the date will be determined and formatted (e.g., Saturday, August 24, 2016), with the result returned to the caller. Because in this case you’re calling displayDate() in conjunction with PHP’s short echo tag syntax, when the date is returned, it will be embedded directly into the surrounding page.
Returning Multiple Values
Once the list() construct executes, $color1, $color2, and $color3 will be assigned red, blue, and green, respectively. List() looks like a function but it is actually a language construct and used on the left side of the assign operator(=) compared to functions that are used on the right-hand side to calculate and return values that are assigned.
Passing Arguments by Value
This function accepts two parameters, aptly named $price and $tax, which are used in the calculation. Although these parameters are intended to be floating points, because of PHP’s weak typing, nothing prevents you from passing in variables of any data type, but the outcome might not be what you expect. In addition, you’re allowed to define as few or as many parameters as you deem necessary; there are no language-imposed constraints in this regard.
When you pass an argument in this manner, it’s called passing by value. This means that any changes made to those values within the scope of the function are ignored outside of the function. In essence the interpreter creates a copy of each variable. If you want these changes to be reflected outside of the function’s scope, you can pass the argument by reference, introduced next.
Note
Unlike languages such as C++, PHP does not require you to define the function before it’s invoked because the entire script is read into the PHP parsing engine before execution. One exception is if the function is defined in an include file, the include/require statement will have to be executed before the function is used.
Default Argument Values
Using Type Declarations
In the example above, a fatal error will be invoked if the function tries to return anything but true or false.
Recursive Functions
Recursive functions , or functions that call themselves, offer considerable practical value to the programmer and are used to divide an otherwise complex problem into a simple case, reiterating that case until the problem is resolved.
The Payment Calculator Function, amortizationTable()
After setting pertinent variables and performing a few preliminary calculations, Listing 4-2 invokes the amortizationTable() function. Because this function calls itself recursively, all amortization table calculations will be performed internal to this function; once complete, control is returned to the caller.
A Payment Schedule Calculator Using Recursion
Anonymous Functions
When a function is declared with a name and a parameter list, it can be called from anywhere in the code where it’s defined. In some cases, it makes sense to define a function that is only callable from a specific location. This often used for callback functions where a specific function is called as a result of calling another function. These functions are called anonymous functions or closures. They do not have a function name.
In the first section, the global variable $a is not accessible, causing it to be assigned 0 inside the first closure. In the second section, $a is made available to the closure, but the global value is no affected. In the last section, the global variable $a is made available by reference. This causes the global value to change when the closure is executed.
Function Libraries
Save this library, preferably using a naming convention that will clearly denote its purpose, such as library.taxation.php. Do not, however, save this file within the server document root using an extension that would cause the web server to pass the file contents unparsed. Doing so opens up the possibility for a user to call the file from the browser and review the code, which could contain sensitive data. If you deploy the code on a server where you are in full control over the hard disk and the configuration of the web server, it is recommended that include files are stored outside of the web root. This can be in a folder called include or libraries. If, on the other hand, you are deploying to a shared hosting environment, you might only get access to a single folder, the web root. In that case, it’s important that your library and configuration files use the .php extension. This will ensure they are passed through the PHP interpreter if they are called directly. In that case, they will simply produce an empty document, although any code that is outside of a function will be executed and could return content that will be part of the output.
Assuming the vendor folder is outside of the web root, this script will use the configured include_path to look for the directory and file. This is commonly used for libraries installed with Composer. Once included, any of the three functions found in these libraries can be invoked as needed.
Summary
This chapter concentrated on one of the basic building blocks of modern programming languages: reusability through functional programming. You learned how to create and invoke functions, pass information to and from the function block, nest functions, and create recursive functions. Finally, you learned how to aggregate functions together as libraries and include them into the script as needed.
The next chapter introduces PHP’s array features, covering the language’s vast swath of array management and manipulation capabilities.