Home  >  Article  >  Backend Development  >  php automatic loading method

php automatic loading method

不言
不言Original
2018-04-14 09:14:181594browse

The content of this article is about the automatic loading method of php. Now I share it with you. Friends in need can refer to the content of this article.

php loading File method:
1, include, include_once, requice, requice_one regular loading
2, __autoload()

3. spl_autoload_register()

##Conventional loading method Assume we have a class file A.php, It defines a class named A:

Then we have an index.php that needs to use this class A. The conventional writing method is

But there is a problem, if our index.php needs to contain not only class A, but many classes, in this way, many lines of require must be written Statements can sometimes make people feel uncomfortable.

__autoload() automatically loads
But in versions after php5, we no longer need to do this.
In php5, the __autoload function is automatically called when trying to use a class that has not been defined, so we can write the __autoload function to let php automatically load the class without having to write a long list of include files.

For example, in the above example, index.php can be written like this:

Of course the above is just the simplest demonstration, __autoload just goes include_path finds class files and loads them. We can define __autoload rules for loading classes according to our own needs. Note: Since __autoload() is a function, it can only exist once.

spl_autoload_register()自动加载
但现在问题来了,如果在一个系统的实现中,如果需要使用很多其它的类库,这些类库可能是由不同的开发人员编写的,其类名与实际的磁盘文件的映射规则不尽相同。这时如果要实现类库文件的自动加载,就必须在__autoload()函数中将所有的映射规则全部实现,这样的话__autoload()函数有可能 会非常复杂,甚至无法实现。最后可能会导致__autoload()函数十分臃肿,这时即便能够实现,也会给将来的维护和系统效率带来很大的负面影响。在这种情况下,难道就没有更简单清晰的解决办法了吧?答案当然是:NO!

spl_autoload_register() 满足了此类需求。 它实际上创建了 autoload 函数的队列,按定义时的顺序逐个执行。相比之下, __autoload() 只可以定义一次。

bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )
我们继续改写上面那个例子:

或者直接使用匿名函数:

这样子也是可以正常运行的,这时候php在寻找类的时候就没有调用__autoload而是调用我们自己定义的函数loader了。同样的道理,下面这种写法也是可以的:

更多示例
autoload.php

建议入口文件里养成定义绝对地址SDK_PATH的习惯,这样require不会出错。
以上就是本文的全部内容,希望对大家的学习有所帮助。

相关推荐:

深度总结 PHP自动加载

PHP自动加载的实例详解

深入学习php自动加载机制

The above is the detailed content of php automatic loading method. For more information, please follow other related articles on the PHP Chinese website!

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