Home >Backend Development >PHP Tutorial >How to create a PHP function library and use it?
To create a PHP function library, create a new file containing the function definition and use require_once to include the function library into the main script. For example, a math library can define sum and product functions and then use them in a script as follows: 1. Define the library; 2. Include the library into the script; 3. Call the library functions.
Create a function library
Create a new PHP file (e.g. functions.php
):
<?php // 定义一个问候函数 function greet($name) { echo "Hello, $name!"; } ?>
Use the function library
Include the function library into your PHP script:
<?php // 包含函数库 require_once 'functions.php'; // 调用问候函数 greet('John Doe'); ?>
Practical case: Math function library
Create a math function library (math.php
):
<?php // 定义一个求和函数 function sum($a, $b) { return $a + $b; } // 定义一个求乘积函数 function multiply($a, $b) { return $a * $b; } ?>
in your PHP script Math function library used in:
<?php // 包含函数库 require_once 'math.php'; // 调用求和和求乘积函数 $sum = sum(5, 10); $product = multiply(2, 3); echo "求和:$sum" . PHP_EOL; echo "求乘积:$product" . PHP_EOL; ?>
Output:
求和:15 求乘积:6
The above is the detailed content of How to create a PHP function library and use it?. For more information, please follow other related articles on the PHP Chinese website!