Rutwick Gangurde
Rutwick Gangurde

Reputation: 4912

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. 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?

Upvotes: 0

Views: 1439

Answers (1)

Kristian Vitozev
Kristian Vitozev

Reputation: 5971

A \ before the beginning of a class represents the global namespace.

my.class.php

<?php

class myClass {

}

?>

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;

Upvotes: 2

Related Questions