Home > Article > Backend Development > How to create a PHP library and load it?
How to create a PHP function library and load it? Create a function library file containing the functions to be defined. Use include or require statements to load a function library file to make its functions available to the current script.
First, we need to create a file to hold our function library. For the purposes of this tutorial, we will create a file called my_functions.php
:
<?php function greet($name) { echo "Hello $name!\n"; } function add($a, $b) { return $a + $b; }
This file contains two functions: greet()
and add()
.
Next, we need to load the function library file so that we can use the functions in it. There are two ways to do this:
Method 1: Using the include
include
statement will specify The contents of the file are inserted into the current script. To load the function library, we can use the following syntax:
include 'my_functions.php';
Method 2: Use the require
require
statement with include
Similar, but it generates a fatal error if the specified file does not exist or cannot be read. The syntax is as follows:
require 'my_functions.php';
Once the function library is loaded, we can use the functions in it. Let’s see an example of greeting the user using the greet()
function:
<?php include 'my_functions.php'; $name = 'John'; greet($name); // 输出:Hello John!
We can also use the add()
function to calculate the sum of two numbers:
<?php include 'my_functions.php'; $num1 = 5; $num2 = 10; $sum = add($num1, $num2); // $sum 现在等于 15
The above is the detailed content of How to create a PHP library and load it?. For more information, please follow other related articles on the PHP Chinese website!