站长资讯网
最全最丰富的资讯网站

php引入文件的方法有哪些

php引入文件的方法有哪些

PHP中引入文件的方法有:include、require、include_once、require_once。

区别介绍:

include和require

include有返回值,而require没有返回值。

include在加载文件失败时,会生成一个警告(E_WARNING),在错误发生后脚本继续执行。所以include用在希望继续执行并向用户输出结果时。

//test1.php <?php include './tsest.php'; echo 'this is test1'; ?>  //test2.php <?php echo 'this is test2n'; function test() {     echo 'this is testn'; } ?>  //结果: this is test1

require在加载失败时会生成一个致命错误(E_COMPILE_ERROR),在错误发生后脚本停止执行。一般用在后续代码依赖于载入的文件的时候。

//test1.php <?php require './tsest.php'; echo 'this is test1'; ?>  //test2.php <?php echo 'this is test2n'; function test() {     echo 'this is testn'; } ?>

结果:

php引入文件的方法有哪些

include和include_once

include载入的文件不会判断是否重复,只要有include语句,就会载入一次(即使可能出现重复载入)。而include_once载入文件时会有内部判断机制判断前面代码是否已经载入过。

这里需要注意的是include_once是根据前面有无引入相同路径的文件为判断的,而不是根据文件中的内容(即两个待引入的文件内容相同,使用include_once还是会引入两个)。

//test1.php <?php include './test2.php'; echo 'this is test1'; include './test2.php'; ?>  //test2.php <?php echo 'this is test2'; ?>  //结果: this is test2this is test1this is test2   //test1.php <?php include './test2.php'; echo 'this is test1'; include_once './test2.php'; ?>  //test2.php <?php echo 'this is test2'; ?>  //结果: this is test2this is test1   //test1.php <?php include_once './test2.php'; echo 'this is test1'; include './test2.php'; ?>  //test2.php <?php echo 'this is test2'; ?>  //结果: this is test2this is test1this is test2   //test1.php <?php include_once './test2.php'; echo 'this is test1'; include_once './test2.php'; ?>  //test2.php <?php echo 'this is test2'; ?>  //结果: this is test2this is test1

require和require_once:同include和include_once的区别相同。

赞(0)
分享到: 更多 (0)