简体   繁体   English

PHP名称空间-如何包含不在名称空间中的第三方库?

[英]PHP namespaces - How to include third party libraries which are not in a namespace?

I am using an autoloader which includes classes based on WordPress naming convention, meaning, My_Class should reside in class-my-class.php . 我正在使用自动加载器,其中包括基于WordPress命名约定的类,这意味着My_Class应该驻留在class-my-class.php It works fine. 工作正常。 However, I have to use a third party library, which is differently named and doesn't use a namespace. 但是,我必须使用第三方库,该库的名称不同,并且不使用名称空间。 How would I use it in my code? 如何在代码中使用它? Do I need to include it explicitly? 我是否需要明确包含它?

A \\ before the beginning of a class represents the global namespace. 类开始之前的\\表示全局名称空间。

my.class.php my.class.php

<?php

class myClass {

}

?>

index.php index.php

<?php

require( 'my.class.php' );

$obj = new \myClass;

var_dump( $obj );

?>

Anyway, if you want to autoload a class without namespace, you can use the following trick in your autoloader: 无论如何,如果要自动加载没有名称空间的类,则可以在自动加载器中使用以下技巧:

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

$obj = \myClass;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM