功能类型 | 典型应用 | 代码示例 |
---|---|---|
无参函数 | 固定功能模块封装 | function showVersion() { |
带参函数 | 动态计算场景 | function calcArea($r) { |
PHP支持多种参数处理方式,默认参数设置可有效提升函数灵活性。当调用函数时未指定参数值,预定义的默认参数将自动生效。
function formatPrice($value, $symbol = '¥') { return $symbol . number_format($value, 2);}echo formatPrice(199); // 输出 ¥199.00
全局变量在函数内部使用时需显式声明,通过global关键字或$GLOBALS超全局数组均可实现跨作用域访问。
$counter = 0;
function increment() {
global $counter;
$counter++;
}
function resetCounter() {
$GLOBALS['counter'] = 0;
}
通过文件包含机制实现代码复用,include与require的主要区别在于错误处理方式。建议在关键模块加载时使用require确保执行可靠性。
典型文件包含结构示例:
// config.php
define('API_KEY', 'xxxxxx');
// main.php
require_once 'config.php';
function fetchData() {
// 使用API_KEY常量
}