美文网首页PHP ChaosPHP学习程序员
PHP 实现类的自动加载

PHP 实现类的自动加载

作者: xiaojianxu | 来源:发表于2017-01-06 18:21 被阅读68次

    使用 spl_autoload_register() 函数实现类的自动加载

    一个文件中,往往需要使用多个别的类。这种情况下,一般是必须先在文件顶部使用 require/require_once或 include_include_once 进行加载,才能实例函数。

    使用 spl_auto_register() 实现自加载的执行过程输出:

    Trying to loadClass1 via ClassAutoloader::loader()
    Class1::__construct
    Trying to loadClass2 via Class
    Autoloader::loader() Class2::__construct

    spl_autoload_register - Register given function as __autoload() implementation
    
    Description
    
    bool spl_autoload_register([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]])
    
    
    Register a function with the spl provided __autoload queue. If the queue is not yet activated it will be activated.
    
    If your code has an existing __autoload() function then this function must be explicitly registered on the __autoload queue. This is because spl_autoload_register()
    
    will efectively replace the engine cache for the __autoload() function by either spl_autoload() or spl_autoload_call().
    
    If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of 
    them in the order they are defined. By contrast, __autoload() may only be defined once.
    
    

    目录结构:

    • modernphp/ClasssAutoloader.php
    • modernphp/Class1.php
    • mordernphp/Class2.php

    ClassAutokloader.php

    class ClassAutoloader 
    {
        
        public function __construct() {
            spl_autoload_register(array($this, 'loader'));
        }
        
        public function loader($className) {
            
            echo "Trying to load" , $className, ' via ', __METHOD__, "()\n";
            echo "<br/>";
            include $className . '.php';
        }
        
    }
    
    $autoloader = new ClassAutoloader();
    
    $obj = new Class1();
    $obj = new Class2();
    

    Class1.php

    <?php
    
    class Class1
    {
        
        public function __construct()
        {
            
            echo __METHOD__;
            echo "<br/>";
        }
    }
    

    Class2.php

    <?php
    
    class Class1
    {
        
        public function __construct()
        {
            
            echo __METHOD__;
            echo "<br/>";
        }
    }
    

    相关文章

      网友评论

        本文标题:PHP 实现类的自动加载

        本文链接:https://www.haomeiwen.com/subject/tditbttx.html