Page 1 of 1

Check if a string contains a valid class name

Posted: Sun Aug 06, 2006 4:36 pm
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

Posted: Sun Aug 06, 2006 4:40 pm
by feyd
class_exists()

and store the __CLASS__ magic constant into a variable first.

Posted: Sun Aug 06, 2006 4:40 pm
by Weirdan

Posted: Sun Aug 06, 2006 5:09 pm
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.

Posted: Sun Aug 06, 2006 5:11 pm
by feyd
instanceof works with both classes and subclasses, while is_subclass_of() .. well you can guess what that works on.

Posted: Sun Aug 06, 2006 5:19 pm
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)