Heim  >  Artikel  >  Backend-Entwicklung  >  php中的多余的require(),这样会导致多余的执行时间吗?

php中的多余的require(),这样会导致多余的执行时间吗?

WBOY
WBOYOriginal
2016-06-06 20:45:341099Durchsuche

在php中,我们有时会在一个初始化文件(eg:ini.php)中通过require()函数引入多个文件。
eg:在ini.php中

<code class="lang-php">require 'a.php';
require 'b.php';
require 'c.php';
require 'd.php';
</code>

然后,我们会在某个脚本里(eg:example.php),

<code class="lang-php">require 'ini.php';
</code>

但问题是:在example.php中,我们只需要用到a.php和b.php里面的函数,而不需要c.php和d.php,那这样会不会导致php在require的时候,由于引入了多余的文件,而耗费了多余的执行时间,从而影响效率呢?

回复内容:

在php中,我们有时会在一个初始化文件(eg:ini.php)中通过require()函数引入多个文件。
eg:在ini.php中

<code class="lang-php">require 'a.php';
require 'b.php';
require 'c.php';
require 'd.php';
</code>

然后,我们会在某个脚本里(eg:example.php),

<code class="lang-php">require 'ini.php';
</code>

但问题是:在example.php中,我们只需要用到a.php和b.php里面的函数,而不需要c.php和d.php,那这样会不会导致php在require的时候,由于引入了多余的文件,而耗费了多余的执行时间,从而影响效率呢?

引入不需要的c.phpd.php会有一定的效率损耗(首先是额外的读硬盘,另外就是看你在这两个php文件里做了些什么操作——无论如何有额外损耗)。

你可以根据不同的页面在ini.php里判断需要引入的文件,如:

<code class="lang-php">$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if( stripos($url, 'page1') ){
    require 'a.php';
    require 'b.php';
}
else{
    require 'c.php';
    require 'd.php';
}
</code>

像我们平时开发时,会使用一个Loader类来加载需要的文件,突出一个按需加载,你可以参考一下:

<code class="lang-php"><?php class Loader{

    private static function _require($file_path){
      if(file_exists($file_path)) require_once $file_path;
    }

    public static function db($file){
      self::_require(ROOT_PATH."db/$file.php");
    }

    public static function utils($file){
      self::_require(ROOT_PATH."utils/$file.php");
    }

    public static function module($file, $type = "index"){
      self::_require(ROOT_PATH."module/$type/$file.action.php");
    }

    public static function assets($file){
      $file_path = ROOT_PATH."view/$file";
      if(file_exists($file_path))
        return file_get_contents($file_path);
    }

  }
?>

</code>

autoloader是必须的,PHP程序应该只在autoloader的实现内部有一个require,然后最多在入口文件有第二个require来加载autoloader,其余的require都是耍流氓

参考我的激进版本PHP开发实践

顺便,还有个更恶劣的东西叫require_once ,被PHP开发组的laruence建议避免使用

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn