【问题标题】:PHP namespaces - How to include third party libraries which are not in a namespace?PHP 命名空间 - 如何包含不在命名空间中的第三方库?
【发布时间】:2015-10-09 05:18:52
【问题描述】:

我正在使用一个自动加载器,其中包含基于 WordPress 命名约定的类,这意味着 My_Class 应该驻留在 class-my-class.php 中。它工作正常。但是,我必须使用名称不同且不使用命名空间的第三方库。我将如何在我的代码中使用它?我需要明确地包含它吗?

【问题讨论】:

    标签: php wordpress oop namespaces


    【解决方案1】:

    类开头之前的\ 表示全局命名空间。

    我的.class.php

    <?php
    
    class myClass {
    
    }
    
    ?>
    

    index.php

    <?php
    
    require( 'my.class.php' );
    
    $obj = new \myClass;
    
    var_dump( $obj );
    
    ?>
    

    无论如何,如果你想自动加载一个没有命名空间的类,你可以在你的自动加载器中使用以下技巧:

    if ( file_exists( $filepath = str_replace( '\\', '/', $class ) ) { 
         require $filepath;
    }
    
    $obj = \myClass;
    

    【讨论】:

    • 谢谢!所以我必须明确要求图书馆的文件?
    • 再次感谢,我在启动自动加载器的引导文件中需要该文件,并将该类与全局命名空间一起使用。
    猜你喜欢
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2015-07-08
    • 2016-10-23
    相关资源
    最近更新 更多