There are two ways to reuse PHP custom functions: 1. Include function files; 2. Automatically load functions. Inclusion method: Define the function in a separate file and then include the file where needed. Automatic loading method: Use PHP's SPLAutoload mechanism to automatically load custom functions. Example: Format date function, inclusion method: define the function in the functions.php file, and include the file in the main.php file; automatic loading method: define the function in the format_date.php file, in the main.php file Register the autoloading function to automatically load the format_date.php file.
How to reuse PHP custom functions
In large PHP projects, reusing code can significantly improve development efficiency. Custom functions are an effective way to reuse code.
Method 1: Include function file
Define the custom function in a separate file (functions.php
), and then add it to the required The location contains this file.
// functions.php function my_custom_function($arg1, $arg2) { // ... 函数逻辑 ... } // main.php require_once 'functions.php'; my_custom_function('foo', 'bar');
Method 2: Automatically load functions
Use PHP’s SPLAutoload mechanism to automatically load custom functions.
// my_custom_function.php function my_custom_function($arg1, $arg2) { // ... 函数逻辑 ... } // main.php spl_autoload_register(function ($class) { if (file_exists(__DIR__ . "/functions/$class.php")) { require "$class.php"; } }); my_custom_function('foo', 'bar');
Practical case
Suppose you need to create a function that formats dates.
Method 1: Include function file
// functions.php function format_date($date, $format) { return date($format, strtotime($date)); } // main.php require_once 'functions.php'; $formatted_date = format_date('2023-03-08', 'Y-m-d'); echo $formatted_date; // 输出: 2023-03-08
Method 2: Automatically load function
// format_date.php function format_date($date, $format) { return date($format, strtotime($date)); } // main.php spl_autoload_register(function ($class) { if (file_exists(__DIR__ . "/functions/$class.php")) { require "$class.php"; } }); $formatted_date = format_date('2023-03-08', 'Y-m-d'); echo $formatted_date; // 输出: 2023-03-08
The above is the detailed content of How to reuse PHP custom functions?. For more information, please follow other related articles on the PHP Chinese website!