在PHP中:
什么时候应该使用require和include? 什么时候应该使用require_once vs. include_once?
在PHP中:
什么时候应该使用require和include? 什么时候应该使用require_once vs. include_once?
当前回答
_once函数与不含_once函数的区别: 没有_once函数的代码将被再次包含,而有_once函数的PHP会跟踪被包含的文件,并且只包含它一次。
require和include的区别: 如果没有找到所需的文件,PHP将发出致命错误,而for include只会发出警告。
其他回答
Require的开销比include大,因为它必须首先解析文件。用包含替换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();
}
}
?>
除非您担心加载一个可能只在某些条件下使用的类的开销,并且不想在不使用时加载它。
require文件必须存在,如果不存在则会显示错误;而使用include -如果文件不存在,那么页面将继续加载。
_once函数与不含_once函数的区别: 没有_once函数的代码将被再次包含,而有_once函数的PHP会跟踪被包含的文件,并且只包含它一次。
require和include的区别: 如果没有找到所需的文件,PHP将发出致命错误,而for include只会发出警告。
我使用的函数如下:
function doSomething() {
require_once(xyz.php);
....
}
在xyz.php中声明了常量值。
我必须从另一个PHP脚本文件调用这个doSomething()函数。
但是我观察到在循环中调用此函数时的行为,对于第一次迭代doSomething()在xyz.php中获得常量值,但后来每次迭代doSomething()都无法获得xyz.php中声明的常量值。
我通过从require_once()切换到include()来解决我的问题,更新的doSomething()代码如下:
function doSomething() {
include(xyz.php);
....
}
现在对doSomething()的每次迭代调用都得到xyz.php中定义的常量值。