mercredi 26 octobre 2016

Instantiating a class with reflection vs from variable

I am wondering why one would choose reflection over instantiating simply by variable in these 2 scenarios for the FactoryAbstract.

Concrete class

class Factory extends FactoryAbstract
{
    const CONSTANT = '\Namespace\Sub\Sub';
}

FactoryAbstract 1

abstract class FactoryAbstract
{
    public function __construct()
    {
        $className = $this::CONSTANT;
        $instance = new ReflectionClass($className);

        if (!$instance->isSubclassOf('\\Namspace\\Sub\\Whatever')) {
            throw new LogicException('Concrete implementation must be a subclass of the Whatever class');
        }
    }
}

FactoryAbstract 2

abstract class FactoryAbstract
{
    public function __construct()
    {
        $className = $this::CONSTANT;
        $instance = new $className();

        if (!is_subclass_of($instance, '\\Namspace\\Sub\\Whatever')) {
            throw new LogicException('Concrete implementation must be a subclass of the Whatever class');
        }
    }
}

This is not tested code but a simple code gist, in the second example you have to strip the leading backslash for it to even work, etc.

What is the advantage of using reflection like in the FactoryAbstract of the first example?

I know reflection is resource intensive and it is better to stay away from it whenever you can but I am wondering if there is a big performance difference between instantiating a reflection class vs instantiating from a variable.

It seems like in the first example(which is in the code base) there is no advantage to using a reflection class since the is_subclass_of method is available a function as well besides the reflection API.

Hopefully my examples are clear enough, if you need some more information let me know.





Aucun commentaire:

Enregistrer un commentaire