Home  >  Article  >  Backend Development  >  __autoload 中是不是一定需要 require_once?

__autoload 中是不是一定需要 require_once?

WBOY
WBOYOriginal
2016-06-06 20:33:12913browse

看到 __autoload 连官方手册都是 require_once,但是自己测试的时候,如果文件已经加载过了,是不会再执行加载的:

【index.php】

<code><?php function __autoload($className)
{
    echo 'autoload';
    require($className.'.php');
}

$obj = new sample();
$obj = new sample();
$obj = new sample();
$obj = new sample();
$obj = new sample();
</code></code>

【sample.php】

<code><?php class sample{}
</code></code>

index.php 和 sample.php 同目录,事实上最后只输出了一次 'autoload' 字符串。

那这么说来,是不是用 require 就可以了,何必用 once 造成不必要的性能浪费呢?

回复内容:

看到 __autoload 连官方手册都是 require_once,但是自己测试的时候,如果文件已经加载过了,是不会再执行加载的:

【index.php】

<code><?php function __autoload($className)
{
    echo 'autoload';
    require($className.'.php');
}

$obj = new sample();
$obj = new sample();
$obj = new sample();
$obj = new sample();
$obj = new sample();
</code></code>

【sample.php】

<code><?php class sample{}
</code></code>

index.php 和 sample.php 同目录,事实上最后只输出了一次 'autoload' 字符串。

那这么说来,是不是用 require 就可以了,何必用 once 造成不必要的性能浪费呢?

  1. 你应该能明白 __autoload 是什么时候触发的吧???
    在你第一次触发之后, 你成功的加载了 拥有这个class的php文件,
    那么 当你第二次new它的时候, 已经存在了这个class, 就不会再次触发 __autoload 了的.

  2. 官方没有规定说必须使用 require_once 吧? 那个只是例子吧.
    http://php.net/manual/zh/function.autoload.php

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn