LeanCloud中的PHP autoload

官方是这么说的 自动加载类

很多开发者写面向对象的应用程序时对每个类的定义建立一个 PHP 源文件。一个很大的烦恼是不得不在每个脚本开头写一个长长的包含文件列表(每个类一个文件)。 在 PHP 5 中,不再需要这样了。可以定义一个 __autoload() 函数, 它会在试图使用尚未被定义的类时自动调用。通过调用此函数,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。

最新的发展情况是

tip:
spl_autoload_register() 提供了一种更加灵活的方式来实现类的自动加载。因此,不再建议使用 __autoload()函数,在以后的版本中它可能被弃用。

一点想法

<pre>
相较于.Net的Namespace, PHP的namespace除了用来方便引用class,组织代码结构,也用来提供需要文件的路径查找。
脚本语言与编译型语言的差异可见一斑。
</pre>

下面是LeanCloud的autoload
主要思路是通过$classname 拆分出是否是leancloud的class,并通过分解namespace classname得到php文件的路径,并require到项目中来。

/**
 * Enable autoload
 * 
 * Require this file to enable autoload SDK classes on the fly. If you're
 * using composer, it should be required automatically.
 *
 * @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
 *
 * @param string $class 完整的class名字.
 * @return void
 */

spl_autoload_register(function ($class) {

    // project-specific namespace prefix
    $prefix = 'LeanCloud\\';

    // base directory for the namespace prefix
    $base_dir = __DIR__ . '/LeanCloud/';

    // does the class use the namespace prefix?
    /* 
      strlen 获取leanCloud字符的长度,
      strncmp **判断两个字符串前n个字符是否相等,区分大小写**
      比较截取长度为$len的两个字符串是否一致 
    */
    
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return;
    }

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace
    // namespace separators with directory separators in the relative
    // class name, append with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    // if the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});

扩展阅读
require()、require_once()、include()和include_once()的区别

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 在PHP开发过程中,如果希望从外部引入一个class,通常会使用include和require方法,去把定义这...
    四月不见阅读 1,168评论 0赞 0
  • 一、数组 1、数组定义 数组就是一个键值对组成的语言结构,键类似于酒店的房间号,值类似于酒店房间里存储的东西。 $...
    空谷悠阅读 912评论 4赞 11
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 180,864评论 25赞 708
  • 课程准备知识 熟悉和了解数据结构的节本概念 熟悉PHP代码的编写 熟悉面向对象的概念 什么是 SPL SPL的基...
    followyounger1阅读 805评论 0赞 3
  • 家有小女两岁半,恬静乖巧稍内敛。 平稳进入幼儿园,作息规律大改观。 积木儿歌啊爱玩,游戏小曲儿喜欢。 感谢老师耐心...
    爱诗的鱼儿阅读 1,292评论 2赞 5

友情链接更多精彩内容