Reputation: 213
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!
Upvotes: 21
Views: 33174
Reputation: 702
As George Steel wrote, it is impossible to check for a namespace. This is because a namespace is not something that exists; only symbols 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)
One way to think about it is the way you think about surnames: there's no such thing as a surname, you can't get a list of all surnames "standalone" without checking all people, and you therefore can't determine directly whether a surname exists; but it is part of a full name (FQN) of a person, and so you can retrieve a person's surname, or check if they belong to a surname.
It's just a way to group things. You can look around and compile a list of all things that are "red". But you can't get a list of all colours that exist.
Upvotes: 7
Reputation: 96
You can't check directly for the existence of a particular namespace, i.e. you'd have to class_exists('Fetch\\SomeClass')
. See this question too: is it possible to get list of defined namespaces
Upvotes: 4
Reputation: 1987
You need to use the entire namespace in the class_exists
I believe. So something like:
class_exists('Fetch\\Server')
Upvotes: 42