Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if class exists within a namespace?

I've got this:

    use XXX\Driver\Driver;  ...  var_dump(class_exists('Driver')); // false         $driver = new Driver(); // prints 123123123 since I put an echo in the constructor of this class         exit; 

Well... this behaviour is quite irrational (creating objects of classes that according to PHP do not exist). Is there any way to check if a class exist under given namespace?

like image 766
Taruo Gene Avatar asked Mar 14 '14 14:03

Taruo Gene


People also ask

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.

Is class defined PHP?

Classes are the blueprints of objects. One of the big differences between functions and classes is that a class contains both data (variables) and functions that form a package called an: 'object'. Class is a programmer-defined data type, which includes local methods and local variables.


2 Answers

In order to check class you must specify it with namespace, full path:

namespace Foo; class Bar { } 

and

var_dump(class_exists('Bar'), class_exists('\Foo\Bar')); //false, true 

-i.e. you must specify full path to class. You defined it in your namespace and not in global context.

However, if you do import the class within the namespace like you do in your sample, you can reference it via imported name and without namespace, but that does not allow you to do that within dynamic constructions and in particular, in-line strings that forms class name. For example, all following will fail:

namespace Foo; class Bar {     public static function baz() {}  }  use Foo\Bar;  var_dump(class_exists('Bar')); //false var_dump(method_exists('Bar', 'baz')); //false  $ref = "Bar"; $obj = new $ref(); //fatal 

and so on. The issue lies within the mechanics of working for imported aliases. So when working with such constructions, you have to specify full path:

var_dump(class_exists('\Foo\Bar')); //true var_dump(method_exists('\Foo\Bar', 'baz')); //true  $ref = 'Foo\Bar'; $obj = new $ref(); //ok 
like image 132
Alma Do Avatar answered Sep 26 '22 17:09

Alma Do


The issue (as mentioned in the class_exists() manual page user notes) is that aliases aren't taken into account whenever a class name is given as a string. This also affects other functions that take a class name, such as is_a(). Consequently, if you give the class name in a string, you must include the full namespace (e.g. '\XXX\Driver\Driver', 'XXX\\Driver\\Driver').

PHP 5.5 introduced the class constant for just this purpose:

use XXX\Driver\Driver; ... if (class_exists(Driver::class)) {     ... } 
like image 24
outis Avatar answered Sep 22 '22 17:09

outis