Instanceof and namespaces

后端 未结 3 2023
南旧
南旧 2020-12-18 21:02

I am facing an unexpected behaviour trying to use the following:

$object instanceof $class

1/ PHP \'instanceof\' keyword and namespaces wor

相关标签:
3条回答
  • 2020-12-18 21:41

    You can test for instances using namespaces, but use the fully qualified class name.

    For your test I would do this:

    $class = "\\Tools\\Tests\\Entity\\testObject";
    $object = new $class;
    var_dump($object instanceof $class); //bool(true)
    

    You can also test this way using single quotes and not worry about escaping your backslashes and save yourself a few keystrokes.

    $class = '\Tools\Tests\Entity\testObject';
    $object = new $class;
    var_dump($object instanceof $class); //bool(true)
    
    0 讨论(0)
  • 2020-12-18 21:46

    I use simpler variant

    var_dump($object instanceof \Tools\Tests\Entity\testClass);
    
    0 讨论(0)
  • 2020-12-18 21:52

    You should use ReflectionClass to avoid any execution or behaviours you have in\on this model. Read more aboit ReflectionClass to get more info about class\model we checking. http://php.net/manual/en/class.reflectionclass.php

    foreach ($this->modelNamespaces as $namespace) {
        $reflectionClass = new \ReflectionClass($namespace);
    
        if ($reflectionClass->implementsInterface('common\models\FieldsInCollectionInterface')) {
            // class is implemented by FieldsInCollectionInterface
        }
    }
    
    0 讨论(0)
提交回复
热议问题