How to check the existence of a namespace in php

27,151

Solution 1

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

class_exists('Fetch\\Server')

Solution 2

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)

Solution 3

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

Share:
27,151

Related videos on Youtube

Maxim Seshuk
Author by

Maxim Seshuk

Updated on January 14, 2020

Comments

  • Maxim Seshuk
    Maxim Seshuk over 4 years

    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!

  • ars265
    ars265 over 10 years
    sorry, no preceding backslash, updating the answer
  • ars265
    ars265 over 10 years
    It's a nice ability to do this but can be very (processor) time consuming if you have many classes, which is where you would be most likely to use namespaces.
  • DrLightman
    DrLightman about 7 years
    Double slashes are not needed in single quote string. class_exists('Fetch\Server')
  • Bitterblue
    Bitterblue over 5 years
    The answer is either strange or incomplete. Please add a note that you need to check the existance of a class in that namespace. So we can't check the namespace alone.