search
HomeBackend DevelopmentPHP Tutorialphp中autoload的用法总结_PHP

PHP中提供了Autoload来帮助我们方便的进行文件的包含,但是autoload并非想象的那样能够处理所有的情况,今天就来记录一下前几天遇到的autoload存在的一些问题。

为什么要使用 Autoload

在PHP中使用类时,我们必须在使用前加载进来,不管是通过 require 的方式还是 include 的方式,但是会有两个问题影响我们做出加载的决定。

首先是不知道这个类文件存放在什么地方,另外一个就是不知道什么时候需要用到这个文件。特别是项目文件特别多时,不可能每个文件都在开始的部分写很长一串的 require ….

在PHP5之后,我们可以通过 __autoload来解决这个问题。 而且在PHP5.1之后,还提供了 spl_autoload_register() 来提供更完善的加载机制。

通过阅读了 Autoloading in PHP 这篇文章,我理解的 Autoload 的加载机制,当通过 new 来实例化一个类时,PHP会通过定义的__autoload 函数加载相应的文件,如果这个类文件使用了 extends 或者 implements 需要用到其他的类文件,php会重新运行 autoload 去进行类文件的查找和加载,如果发生了两次对同一类文件的请求,就会报错。原文作者提供了三个很有趣的例子来说明这个问题,可以通过 这里 下载源码查看。

一般情况下,有很多种方法来解决加载时到相应位置查找文件的方法。用的最多的就是指定特定的命名标准。

Zend的方法

zend推荐了一种最流行的办法,在文件名中包含路径。例如下面的例子:

// Main.class

function __autoload($class_name) {
    $path = str_replace('_', DIRECTORY_SEPARATOR, $class_name);
    require_once $path.'.php';
}

$temp = new Main_Super_Class(); 所有的下划线都会被替换成路径中的分隔符,上例中就会去 Main/Super/Class.php文件

这种方法的缺点是在编码过程中,我们必须明确的知道代码文件应当所处的位置,而且由于

将文件路径硬编码在了类名中,如果需要修改文件夹的结构时,我们必须手工修改所有的类名。

'Include All'方法

如果是在一个开发环境中,并且对于速度不是很在意的话,使用这个方法是非常方便的。通过将所有类文件放在一个或几个特定文件夹中,然后通过遍历的方式查找加载。

例如:
复制代码 代码如下:
  $arr = array (
    'Project/Classes',
    'Project/Classes/Children',
    'Project/Interfaces'
  );

  foreach($arr as $dir) {
    $dir_list = opendir($dir);

    while ($file = readdir($dir_list)) {
      $path = $dir.DIRECTORY_SEPARATOR.$file;
      if(in_array($file, array('.', '..')) || is_dir($path))
        continue;

      if (strpos($file, ".class.php"))
        require_once $path;
    }
  }
?>

关联文件和位置

另外一个方法是在类文件和他的位置之间建立关联的配置文件,例如:
复制代码 代码如下:
// configuration.php
array_of_associations = array(
  'MainSuperClass' = 'C:/Main/Super/Class.php',
  'MainPoorClass' = 'C:/blablabla/gy.php'
);

调用的文件
复制代码 代码如下:
  require 'autoload_generated.php';

  function __autoload($className) {
    global $autoload_list;
    require_once $autoload_list[$className];
  }

  $x = new A();
?>

当然,如果文件特别多的时候,维护起来会是一件麻烦事,但是与在类名中硬编码位置,哪个更好呢?

我们当然不希望手工来维护这个列表,那么可以使用自动生成这个文件来实现,这个对应关系的文件可以是php\xml\json等等。原文的作者实现了一个这样的工具,仔细考虑一下的话,这个不是很难实现,原文作者甚至发展了一个小型的 Autoload 框架,值得学习。

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.