Check if a string contains a valid class name

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Check if a string contains a valid class name

Post by Ollie Saunders »

I tried this:

Code: Select all

class A
{

}

class B {
    public static function testInstanceOf($enforceType)
    {
        return __CLASS__ instanceof $enforceType;
    }
}
var_dump(B::testInstanceOf('A')); // does A exist as a class?
But i got "Fatal error: Invalid opcode 138/1/1" which I was quite proud of actually.
Interestingly if I use self instead of __CLASS__ it complains that self is an undefined constant!

I've found that this:

Code: Select all

class A
{

}

class B {
    public static function testInstanceOf($enforceType)
    {
        $a = new $enforceType();
    }
}
var_dump(B::testInstanceOf('notaclass'));
Will generate an E_FATAL if the class doesn't exist, but also it also generates errors if the constructor is called with wrong params.

So is reflection my only option?

Edit:

Code: Select all

$reflection = new ReflectionClass($enforceType);
Does a find job, I was worried it was going to be hard :P
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

class_exists()

and store the __CLASS__ magic constant into a variable first.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Seeing as...

Code: Select all

class A {}
class B extends A {}

$b = new B();
$nameA = 'A';
var_dump($b instanceof $nameA);
...outputs bool(true), what is the difference between instanceof and is_subclass_of()? I can see none other than is_subclass_of will probably be slower.
and store the __CLASS__ magic constant into a variable first.
Yeah I noticed that later.
class_exists()
OK I'm going crazy I knew about that.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

instanceof works with both classes and subclasses, while is_subclass_of() .. well you can guess what that works on.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

while is_subclass_of() .. well you can guess what that works on.
... and is_subclass_of works with both instances and class names (strings)
Post Reply