Instanceof和名称空间 [英] Instanceof and namespaces

查看:101
本文介绍了Instanceof和名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用以下代码时,我遇到了意外的行为:

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

$object instanceof $class

1/PHP'instanceof'关键字和名称空间可以很好地协同工作,如官方文档.

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

2/但是,有时反斜杠转义会产生更微妙的(模糊的?)行为,如Ben在

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

在我的代码的某个深处,y设置了一些转储,如下所示:

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)

我的第一个转储类与我的第二个转储中的字符串严格相同. 但是,我的instanceof dump返回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 ?

推荐答案

您可以使用名称空间测试实例,但可以使用

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)

这篇关于Instanceof和名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆