mercredi 18 décembre 2019

Check if class can be instantiated

Say I have a function that creates new instances of a given class:

function createInstance($class) {
    return new $class();
}

$dateTime = createInstance('DateTime');

How can I change the implementation of this method so that it is 'defensive' and doesn't produce an error if the class doesn't exist or cannot be instantiated with a parameterless constructor?

Checking that a class exists is easy:

function createInstance($class) {
    classExists($class)
    return new $class();
}

function classExists($class) {
  if (empty($class) || !class_exists($class))
    throw new InvalidArgumentException("\$class argument invalid - no such class '$class'");
}

However, how do I check that a class can be instantiated?

function createInstance($class) {
    classExists($class)
    if (canCreateInstance($class))
        return new $class();
    else
        throw new InvalidArgumentException("Cannot create instance of $class");
}

function classExists($class) {
  if (empty($class) || !class_exists($class))
    throw new InvalidArgumentException("\$class argument invalid - no such class '$class'");
}

function canCreateInstance($class) {
  // ???
}

I've tried using method_exists($class, '__construct'), but as this REPL demonstrates, this is not reliable because the presense of absense of a __construct() method doesn't determine whether a class can be instantiated. So what does determine this?





Aucun commentaire:

Enregistrer un commentaire