PHP如何实现懒加载(实例详解)
这篇文章主要介绍了PHP实现懒加载的方法,实例分析了php加载的原理与懒加载的实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下。
寻常php的加载是通过include(),require()等方法来加载外部文件,之后再通过实例调用方法或直接调用静态方法,而这样子写引入语句实在很麻烦,有的框架会将特定路径的文件全部引入,直接实例化就能使用,但这样一来有的类包不一定用到,写的类包越多的时候,加载的东西就不少了,影响程序的性能。
通过PHP的反射类 ReflectionClass 可以直接获得对应类的一个反射类:
test.php文件如下:
<?php class test{ public function showName(){ var_dump(__CLASS__); } } ?>
index.php文件如下:
<?php var_dump(get_included_files()); $rf = new ReflectionClass('test'); var_dump(get_included_files()); $testObj = $rf->newInstance(); $testObj->showName(); function __autoload($classname){ $classpath = './' . $classname . '.php'; if (file_exists($classpath)) { require_once($classpath); }else { echo 'class file'.$classpath.'not found!'; } } ?> //array // 0 => string 'D:\code\www\test\index.php'(length=26) //array // 0 => string 'D:\code\www\test\index.php'(length=26) // 1 => string 'D:\code\www\text\test.php'(length=25) //string 'test' (length=4)
实例化一个 ReflectionClass,并传类名进去,就会得到一个对应类的反射类。用实例调用 newInstance就会得到反射类的实例,这样就完成了实例化。
通过 get_included_files() 方法,我们可以看到当前页面引入的文件。在实例化反射类前,只有index.php文件,实例化反射类后,自动引入了一个test.php文件,那么看下上面那段代码,发现有个__autoload()名字的魔术方法,这方法就定义了自动加载文件,而ReflectionClass在当前页面找不到类时,就会调用__autoload()去加载类。这就是自动加载的过程。
想知道__autoload()方法有没有开启,可以通过PHP的标准库SPL中的方法来查看:
var_dump(spl_autoload_functions()); spl_autoload_register('newAutoload'); var_dump(spl_autoload_functions()); $testObj1 = getInstance('test'); $testObj2 = getInstance('test'); $testObj3 = getInstance('test'); function getInstance($class, $returnInstance = false){ $rf = new ReflectionClass($class); if ($returnInstance) return $rf->newInstance(); } function newAutoload($classname){ $classpath = './' . $classname . '.php'; if (file_exists($classpath)) { var_dump('require success'); require_once($classpath); } else { echo 'class file ' . $classpath . ' not found!'; } } //array // 0 => string '__autoload' (length=10) //array // 0 => string 'newAutoload' (length=11) //string 'require success' (length=15)
sql_autoload_functions() 方法是用来查看当前自动加载的方法,当前有个__autoload魔术方法,所以返回了函数名,若没定义自动加载方法的话,返回的是false,而 spl_autoload_register() 方法是通过方法名将一个方法注册到自动加载方法,这里用newAutoload方法来替换__autoload方法。
newAutoload方法中,每执行成功一次,打印一句'require success',这里只打印了一次,说明了虽然实例了3次ReflectionClass('test'),但因为test类已经加载过一次,就不会再执行自动加载的方法。通过getInstance()这种加载类的方法,比以前的include()之类的方便多了,只需要加载这个写了getInstance()方法的文件就可以了。
重写的自动加载方法可以根据需要,通过判断类的名字,定义不同的文件路径。getInstance可以用静态变量保存实例,这也是使用到了设计模式中的单例模式。
【相关教程推荐】
2. php从入门到精通
3. bootstrap教程

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
