这篇文章给大家分享的是有关PHP中的包括和需要有什么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
在PHP中,有两种包含外部文件的方式,分别是包括和需要。他们之间有什么不同呢?
如果文件不存在或发生了错误,需要产生E_COMPILE_ERROR级别的错误,程序停止运行。而包括只产生警告,脚本会继续执行。引用>这就是它们最主要的区别,其他方面需要基本等同于包括。
<李>
被包含文件先按参数给出的路径寻找,如果没有给出目录(只有文件名)时则按照include_path指定的目录寻找。如果在include_path下没找到该文件则包括最后才在调用脚本文件所在的目录和当前工作目录下寻找
李> <李>如果定义了路径不管是绝对路径还是当前目录的相对路径include_path都会被完全忽略
李> <李>包含路径在PHP。ini中定义
李> <李>当一个文件被包含时,其中所包含的代码继承了包括所在行的变量范围。从该处开始,调用文件在该行处可用的任何变量在被调用的文件中也都可用。不过所有在包含文件中定义的函数和类都具有全局作用域
李>除了普通的要求和包括之外,还有require_once和include_once,他们的作用是:
<李>
如果该文件中已经被包含过,则不会再次包含。如同此语句名字暗示的那样,只会包含一次
李> <李>可以用于在脚本执行期间同一个文件有可能被包含超过一次的情况下,想确保它只被包含一次以避免函数重定义,变量重新赋值等问题
李>我们来看些例子:
//,a.php 不存在 include “a.php";//,警告//,require “a.php";//,错误 echo 111年,//,使用包括时111会输出//,file1.php 中只有一行代码echo & # 39; file1 # 39;; require_once & # 39; includeandrequire/file1.php& # 39;;,//file1 require_once & # 39; includeandrequire/file1.php& # 39;;//,注意 include_once & # 39; includeandrequire/file1.php& # 39;;//,注意 include_once & # 39; includeandrequire/file1.php& # 39;;//,注意 require & # 39; includeandrequire/file1.php& # 39;;,//file1 require & # 39; includeandrequire/file1.php& # 39;;,//file1 require & # 39; includeandrequire/file1.php& # 39;;,//file1 require & # 39; includeandrequire/file1.php& # 39;;,//, file1我们可以看出当第一个_once加载成功后,后面不管是require_once还是include_once,都不会再加载这个文件了。而不带_once的则会重复加载文件。
php php & lt; ? echo & # 39; file2: & # 39;,只一个美元,PHP_EOL; echo & # 39; file2: & # 39;,又是;b,美元,PHP_EOL; 时间=美元b “file2"; myFile.php php & lt; ? 时间=美元a & # 39; myfile # 39;; 时间=美元b & # 39; youFile& # 39;; require_once & # 39; includeandrequire/php # 39;; echo 一个美元,PHP_EOL; echo b,美元,PHP_EOL;//,输出结果//file2: myFile//file2: youFile//myFile//file2 file3.php php & lt; ? 时间=美元c & # 39; file3 # 39;; myFile.php php & lt; ? function 测试(){ ,,,require_once & # 39; includeandrequire/file3.php& # 39;; ,,,echo c,美元,PHP_EOL;//, file3 } 测试(); echo $ c, PHP_EOL;,//,空被包含文件中可以获取到父文件中的变量,父文件也可以获得包含文件中的变量,但是,需要注意_once的一个特殊情况。
function foo () { ,,,require_once & # 39; includeandrequire/file3.php& # 39;; ,,,return $ c; } (=1;a<美元=5;美元+ +){ ,,,echo foo (),, PHP_EOL; }//file3//空//空//空//,空使用_once并循环加载时,只有第一次会输出file3。php中的内容,这是为什么呢?因为现在的变量范围作用域在方法中,第一次加载完成后,后面的的文件不会再被加载了,这时后面四次循环并没有$ c被定义,$ c默认就是空值了。
如果两个方法中同时用_once加载了一个文件,第二个方法还会加载吗?
function test1 () { ,,,require_once & # 39; includeandrequire/file1.php& # 39;; } function test2 () { ,,,require_once & # 39; includeandrequire/file1.php& # 39;; } test1 ();//, file1 test2();,//,空PHP中包括的和需要有什么用