在PHP中:

什么时候应该使用require和include? 什么时候应该使用require_once vs. include_once?


当前回答

应该将类和函数定义组织在文件中。

使用require_once()加载依赖项(类、函数、常量)。

使用require()加载类似模板的文件。

使用include_once()加载可选依赖项(类、函数、常量)。

使用include()加载可选的模板类文件。

其他回答

需要关键部分,如授权,并包括所有其他部分。

多重包含是非常糟糕的设计,必须完全避免。所以,*_once并不重要。

对于可重用的PHP模板,使用“include”。使用“require”表示必需的库。

“*_once”很好,因为它检查文件是否已经加载,但它只在“require_once”中对我有意义。

Include()在未找到文件时将生成警告,但require_once()将生成致命错误。

另一件事是之前是否包含了file。然后require_once()将不再包含它。

我使用的函数如下:

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中定义的常量值。

我注意到的一件事是,当使用include时,我只能从包含它的文件中访问包含的文件函数。使用require_once,我可以在第二个required_once文件中运行该函数。

我建议添加

if(file_exists($RequiredFile)){
    require_once($RequiredFile);
}else{
  die('Error: File Does Not Exist');
}

因为当require_once杀死页面时,它有时会返回你的网站文件目录

下面是我做的一个自定义函数来要求文件:

function addFile($file, $type = 'php', $important=false){
    //site-content is a directory where I store all the files that I plan to require_once
    //the site-content directory has "deny from all" in its .htaccess file to block direct connections
    if($type && file_exists('site-content/'.$file.'.'.$type) && !is_dir('site-content/'.$file.'.'.$type)){
        //!is_dir checks that the file is not a folder
        require_once('site-content/'.$file.'.'.$type);
        return 'site-content/'.$file.'.'.$type;
    }else if(!$type && file_exists('site-content/'.$file) && !is_dir('site-content/'.$file)){
        //if you set "$type=false" you can add the file type (.php, .ect) to the end of the "$file" (useful for requiring files named after changing vars)
        require_once('site-content/'.$file);
        return 'site-content/'.$file;
    }else if($important){
        //if you set $important to true, the function will kill the page (which also prevents accidentally echoing the main directory path of the server)
        die('Server Error: Files Missing');
        return false;
    }else{
        //the function returns false if the file does not exist, so you can check if your functions were successfully added
        return false;
    }
}

使用的例子:

$success = addFile('functions/common');

if($success){
    commonFunction();
}else{
    fallbackFunction();
}