Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ToolsTestsEntityestObject#226 (2) {
  private $var_one =>
  NULL
  private $var_two =>
  NULL
}
string(36) "ToolsTestsEntityestObject"
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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
215 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 = 'ToolsTestsEntityestObject';
$object = new $class;
var_dump($object instanceof $class); //bool(true)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...