Groups of Logic: Running Code in Another File in PHP

The PHP code examples we’ve seen so far are mostly self-contained individual files. Any variables or functions that are used are also defined in the same file. As your pro­grams grow, they are easier to manage when you can split the code into different files. The require directive tells the PHP engine to load code located in a different file, making it easy to reuse that code in many places.

For example, consider some of the functions defined earlier in this chapter. We could combine them into one file and save it as restaurant-functions.php, as shown in Example 5-26.

Example 5-26. Defining functions in their own file

<?php

function restaurant_check($meal, $tax, $tip) {

$tax_amount = $meal * ($tax / 100);

$tip_amount = $meal * ($tip / 100);

$total_amount = $meal + $tax_amount + $tip_amount;

return $total_amount;

}

function payment_method($cash_on_hand, $amount) {

if ($amount > $cash_on_hand) {

return ‘credit card’;

} else {

return ‘cash’;

}

}

?>

Assuming Example 5-26 is saved as restaurant-functions.php, then another file could reference it, as shown in Example 5-27, with require ‘restaurant- functions.php’;.

Example 5-27. Referencing a separate file

require ‘restaurant-functions.php’;

/* $25 check, plus 8.875% tax, plus 20% tip */

$totat_bitt = restaurant_check( 25, 8.875 , 20);

/* I’ve got $30 */

$cash = 30;

print “I need to pay with ” . payment_method($cash, $totat_bill);

The require ‘restaurant-functions.php’; line in Example 5-27 tells the PHP engine to stop reading the commands in the file it’s currently reading, go read all the commands in the restaurant-functions.php file, and then come back to the first file and keep going. In this example, restaurant-functions.php just defines some functions, but a file loaded with require can contain any valid PHP code. If that loaded file con­tains print statements, then the PHP engine will print whatever it’s told to print out.

If the require statement can’t find the file it’s told to load, or it does find the file but it doesn’t contain valid PHP code, the PHP engine stops running your program. The include statement also loads code from another file, but will keep going if there’s a problem with the loaded file.

Because organizing your code in separate files makes it easy to reuse common func­tions and definitions, this book relies on it frequently in subsequent chapters. Using require and include also opens the door to easily using code libraries written by other people, which is discussed in Chapter 16.

Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *