在PHP中:
什么时候应该使用require和include? 什么时候应该使用require_once vs. include_once?
在PHP中:
什么时候应该使用require和include? 什么时候应该使用require_once vs. include_once?
当前回答
摘自手册:
require()与include()相同,除了失败时,它也会产生致命的E_COMPILE_ERROR级别的错误。换句话说,它将停止脚本,而include()只发出一个允许脚本继续的警告(E_WARNING)。
对于_once()变量也是如此。
其他回答
还有require和include_once。
所以你的问题应该是…
什么时候应该使用require和include? 什么时候应该使用require_once vs. require
这里描述了1的答案。
require()函数与include()函数相同,只是处理错误的方式不同。如果发生错误,include()函数将生成警告,但脚本将继续执行。require()生成一个致命错误,脚本将停止。
2的答案可以在这里找到。
require_once()语句与require()语句相同,只是PHP会检查文件是否已经包含,如果已经包含,则不会再次包含(require)它。
这通常是一个问题,你是想有条件地加载一个客户端库,还是不管你是否要使用它都直接加载它。
这里有一个具体的例子;详述PCJ的发言。
假设你有一个配置文件存储你的数据库用户名和密码(conf.php):
<?php
//my site configuration file
//For Database
$location='localhost';
$dbuser='yourname';
$userpw='yourpassword';
$database='nameofdatabase';
?>
和一个带有使用数据库的静态函数的类:
<?php
class UsedInLoop {
public static function databaseQuery(){
require(/path/to/conf.php); //require_once will not work here
$db = new mysqli($location, $dbuser, $userpw, $database);
//yada yada yada
}
}
?>
这个静态函数在循环中被迭代调用的另一个函数中使用:
<?php
require_once('path/to/arbitraryObject.php'); //either will likely be OK at this level
$obj = new arbitraryObject();
foreach($array as $element){
$obj->myFunction();
}
?>
您只能要求/包含该类一次。如果在循环的每次迭代中都需要/包含它,则会得到一个错误。但是,每次调用静态函数时都必须包含conf文件。
<?php
class arbitraryObject {
public function myFunction(){
require_once(/path/to/UsedInLoop.php); //This must be require_once. require() will not work
UsedInLoop::databaseQuery();
}
}
?>
当然,将它移到函数之外可以解决这个问题:
<?php
require(/path/to/UsedInLoop.php); //now require() is fine
class arbitraryObject {
public function myFunction(){
UsedInLoop::databaseQuery();
}
}
?>
除非您担心加载一个可能只在某些条件下使用的类的开销,并且不想在不使用时加载它。
_once函数与不含_once函数的区别: 没有_once函数的代码将被再次包含,而有_once函数的PHP会跟踪被包含的文件,并且只包含它一次。
require和include的区别: 如果没有找到所需的文件,PHP将发出致命错误,而for include只会发出警告。
基本上,如果您需要一个错误的路径,PHP会抛出一个致命错误,并调用shutdown函数,但是当您包含一个错误的路径时,PHP将继续执行,但它只会显示一个警告,表明文件不存在。
根据英文单词require, PHP被告知页面或文件的执行取决于所需的文件。
根据我的经验,通常需要重要的文件,如配置文件、数据库类和其他重要的实用程序。
它们都是包含文件的方法。
Require意味着它需要它。Require_once意味着它将需要它,但只需要它一次。包含意味着它将包含一个文件,但不需要它继续。
例子:
Require 'filename'
Require_once 'filename'
Include 'filename'
还有一个include_once函数,它只包含一个文件一次。
Include_once 'filename'
当我用手机打字时,不要用大写字母。