Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the existence of a namespace in php

I have a php library https://github.com/tedivm/Fetch and it uses Fetch namespace and I would like to check its existence in my script.

My script code:

// Load Fetch
spl_autoload_register(function ($class) {
    $file = __DIR__ . '/vendor/' . strtr($class, '\\', '/') . '.php';
    if (file_exists($file)) {
        require $file;

        return true;
    }
});

if (!class_exists('\\Fetch')) {
  exit('Failed to load the library: Fetch');
}
$mail = new \Fetch\Server($server, $port);

but this message is always displayed. But the library is fully working.

Thanks in advance for any help!

like image 635
Maxim Seshuk Avatar asked Aug 20 '13 14:08

Maxim Seshuk


People also ask

What is the namespace in PHP?

Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.

How does PHP namespace work?

Like C++, PHP Namespaces are the way of encapsulating items so that same names can be reused without name conflicts. It can be seen as an abstract concept in many places. It allows redeclaring the same functions/classes/interfaces/constant functions in the separate namespace without getting the fatal error.

Which function is used to check if class is exists or not?

The class_exists() function in PHP checks if the class has been defined. It returns TRUE if class is a defined class, else it returns FALSE.

What is namespace example?

In an operating system, an example of namespace is a directory. Each name in a directory uniquely identifies one file or subdirectory. As a rule, names in a namespace cannot have more than one meaning; that is, different meanings cannot share the same name in the same namespace.


2 Answers

You need to use the entire namespace in the class_exists I believe. So something like:

class_exists('Fetch\\Server')
like image 144
ars265 Avatar answered Sep 20 '22 05:09

ars265


As George Steel wrote, it is impossible to check for a namespace. This is because a namespace is not something that exists; only structures exist within namespaces. See below example:

namespace Foo;

class Bar {
}

var_dump(class_exists('Foo')); // bool(false)
var_dump(class_exists('Foo\Bar')); // bool(true)
like image 44
XedinUnknown Avatar answered Sep 23 '22 05:09

XedinUnknown