Instanceof and namespaces

大城市里の小女人 提交于 2019-11-28 03:12:14

问题


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

$object instanceof $class

1/ PHP 'instanceof' keyword and namespaces work well together, as explained in the official doc.

2/ Sometimes, however, backslash escaping gives in to more subtle (obscure?) behaviour, as Ben kindly explained in this nice post.

Somewhere deep down in my code, y set a couple of dumps as follow:

var_dump($object, $class);
var_dump($object instanceof $class);

which gives me the following output when running my script:

class Tools\Tests\Entity\testObject#226 (2) {
  private $var_one =>
  NULL
  private $var_two =>
  NULL
}
string(36) "Tools\Tests\Entity\testObject"
bool(false)

The class of my first dump is strictly the same as the string in my second dump. However, my instanceof dump returns FALSE. Why ?

I played around with backslashes, with no luck. Maybe I messed up somewhere with namespaces ? The thing is I really don't know how to troubleshoot further down. What should I try ?


回答1:


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)



回答2:


I use simpler variant

var_dump($object instanceof \Tools\Tests\Entity\testClass);



回答3:


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
    }
}


来源:https://stackoverflow.com/questions/23807992/instanceof-and-namespaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!