Is it possible to & ldquo; statically & rdquo; check if an 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 */ }

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


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.