Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is possible to "statically" check if a FQCN is of a given type in PHP?

Would be possible to check statically (meaning without creating an instance) if a string containing a FQCN like $fqcn:

function checkCreatingInstance($fqcn)
{
    // Create a new instance
    $instance = new $fqcn;

    return ($instance instanceof 'MyNamespace\Entity\SendMessage');
}

function checkStatically($fqcn)
{
    /* TODO */
}

$fqcn = 'MyNamespace\Entity\SendSmallTextMessage';
var_dump(checkCreatingInstance($fqcn)); // true

Is of a given type? An example hierarchy:

namespace MyNamespace\Entity;

class SendMessage { /* Stuff */ }

namespace MyNamespace\Entity;

class SendNewsletter extends SendMessage { /* Stuff */ }

namespace MyNamespace\Entity;

class SendSmallTextMessage extends SendMessage { /* Stuff */ }
like image 873
gremo Avatar asked Dec 07 '25 13:12

gremo


2 Answers

Yes. is_a() will do it, if you pass TRUE as the third argument.

Example

The advantage of this is that you can write your function so it accepts and object or a string and it will work either way, you don't have to have two functions for a static and instantiated check:

function checkIsChildOf ($objOrFQCN, $parent)
{
    return is_a($objOrFQCN, $parent, TRUE);
}

Yet another example of the PHP manual being poor - this behaviour is documented in the manual, so far as I can tell but I have no clue why you didn't see it, so the manual is just poor to not make it visible.

like image 65
DaveRandom Avatar answered Dec 10 '25 01:12

DaveRandom


namespace Foo;

class A { }

class B extends A { }

class C { }

is_subclass_of('\Foo\A', '\Foo\A');  // false
is_subclass_of('\Foo\B', '\Foo\A');  // true
is_subclass_of('\Foo\C', '\Foo\A');  // false

http://php.net/is_subclass_of

like image 23
deceze Avatar answered Dec 10 '25 03:12

deceze