<?php
function demonstrateInclude() {
echo "1. include 方法:\n";
// 创建被调用的PHP文件
$targetFile = 'target_script.php';
file_put_contents($targetFile, '<?php
echo "Hello from target_script.php\n";
$message = "数据已处理";
return $message;
');
// 调用方式
$result = include $targetFile;
echo "返回值: $result\n";
// 清理
unlink($targetFile);
}
demonstrateInclude();
target_script.php
<?php
echo 666;
解释:
这段PHP代码完整演示了include语句的使用方法和特性,我来详细解释每个部分:
函数定义:
定义demonstrateInclude()函数来封装演示逻辑
首先输出标题"1. include 方法:"
临时文件创建:
使用file_put_contents()动态创建target_script.php文件
文件内容包含:
输出语句echo "Hello from target_script.php\n"
定义变量$message = "数据已处理"
return $message返回处理结果
include执行:
$result = include $targetFile包含并执行目标文件
被包含文件中的echo语句会立即执行输出
被包含文件的返回值会赋给$result
结果输出:
输出include的返回值:"返回值: 数据已处理"
清理工作:
使用unlink($targetFile)删除临时创建的PHP文件
函数调用:
最后调用demonstrateInclude()执行演示
执行流程:
创建临时PHP文件
包含文件并执行其中的代码
捕获文件返回值
输出执行结果
清理临时文件
输出结果:
textCopy Code
- include 方法:
Hello from target_script.php
返回值: 数据已处理
关键特性演示:
include的文件执行时机(立即执行)
被包含文件的返回值获取
动态文件创建和包含的完整流程
资源清理的最佳实践
注意:这种动态创建临时文件的方式主要用于演示,实际开发中应使用预先存在的文件进行包含操作。