Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

php - How to check if class exists within a namespace?

I've got this:

    use XXXDriverDriver;

...

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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('FooBar')); //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 FooBar;

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('FooBar')); //true
var_dump(method_exists('FooBar', 'baz')); //true

$ref = 'FooBar';
$obj = new $ref(); //ok

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...