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!
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.
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.
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.
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.
You need to use the entire namespace in the class_exists
I believe. So something like:
class_exists('Fetch\\Server')
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With