| Start |
|---|
Inline class definition, no loading required PHP knows what |
Manual class loading with require Here we have three files. One file ("Animal.php") defines the class. This file has no side effects besides defining the class and neatly keeps all the knowledge about an "Animal" in one place. It's easily version controlled. It's easily reused. Two files consume the "Animal.php" file by manually Now imagine we had dozens or hundreds of cases where we wanted to perform |
Autoloading replaces manual class definition loading Compare this to the other examples. Notice how The magic happens with spl_autoload_register (opens new window). This PHP function takes a closure and adds the closure to a queue of closures. When PHP encounters a class for which it has no definition, PHP hands the class name to each closure in the queue. If the class exists after calling a closure, PHP returns to its previous business. If the class fails to exist after trying the entire queue, PHP crashes with "Class 'Whatever' not found." |
Autoloading as part of a framework solution Thanks to our generic autoloader, we have access to any class that follows our autoloader naming convention. In this example, our convention is simple: the desired class must have a file in the same directory named for the class and ending in ".php". Notice that the class name exactly matches the file name. Without autoloading, we would have to manually In the final analysis, PHP autoloading is a mechanism to help you write less mechanical code so you can focus on solving business problems. All you have to do is define a strategy that maps class name to file name. You can roll your own autoloading strategy, as done here. Or, you can use any of the standard ones the PHP community has adopted: PSR-0 (opens new window) or PSR-4 (opens new window). Or, you can use composer (opens new window) to generically define and manage these dependencies. |
| Autoloading with Composer Composer generates a You might simply include this file and you will get autoloading for free.
This makes working with third-party dependencies very easy. You can also add your own code to the Autoloader by adding an autoload section to your In this section you define the autoload mappings. In this example its a PSR-4 (opens new window) mapping of a namespace to a directory: the Important: After adding new entries to the autoload section, you have to re-run the command In addition to When you including the Syntax
RemarksAutoloading, as part of a framework strategy, eases the amount of boilerplate code you have to write. |
Read Article
https://develop.horje.com/learn/1434/reference