Modularizing Code

A common requirement in PHP development is to reuse parameters and functions across many scripts. For example, you might want to use the username and password credentials many times to connect to the MySQL server, or you might have a function such as showerror() (described earlier in Handling MySQL Errors”) that you want to call from many different places. This section shows you how to do this effectively.

PHP has four built-in functions for including scripts in other scripts. These allow you to share variables and functions between those scripts without duplicating them, making it much easier to maintain code and decreasing the chance of bugs through duplication and redundancy. The functions are include(), require(), require_once(), and include_once(). We discuss the two require variants here, which are identical to the include variants in every way, except what happens when an error occurs: include() triggers a PHP WARNING (which, by default, doesn’t stop the script), while require() triggers a fatal ERROR that stops script execution.

Suppose you have the following code that you want to reuse across several scripts:

<?php
 $username = "root";
 $password = "the_mysql_root_password";
 $database = "music";
 $host = "localhost";

 // Custom error handler function
 function showerror($connection)
 {
  die(mysqli_error($connection) . " (" . mysqli_errno($connection) . ")");
 }
?>

It’s stored in the file db.php. You can reuse it with the require() directive. Here’s an example, in ...

Get Learning MySQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.