82

I need to check if a variable is an object of the User type.

User is my class $user my object

$this->assertInstanceOf($user, User);

This is not working. I have a the following error: use of undefined constant User - assumed 'User'.

0

3 Answers 3

151

https://docs.phpunit.de/en/9.5/assertions.html#assertinstanceof

I think you are using this function wrong. Try:

$this->assertInstanceOf('User', $user);

As of PHP 5.5 you can also use:

$this->assertInstanceOf(User::class, $user);

(From @james2doyle in comments.)

Sign up to request clarification or add additional context in comments.

Comments

66

It's always a good idea to use ::class wherever you can. If you get used to this standard, you don't have to use FQCNs (fully qualified classnames), or escape backslashes. Also, IDEs provide better functionality if they know that User here is not just a string, but rather a class.

$this->assertInstanceOf(User::class, $user);

4 Comments

I fully agree with this statement, but it sounds more like a comment on the accepted answer than like a separate answer...
I think this is the required way on PHP Unit 9.5.
Why is it a good idea to use ::class?
@PeterMortensen Because it could be a string, as he says
7

Or you can use something like:

$this->assertInstanceOf(get_class($expectedObject), $user);

I usually use this when I'm checking i.e. if setter method is returning reference to self.

$testedObj = new ObjectToTest();
$this->assertInstanceOf(
    get_class($testedObj),
    $testedObj->setSomething('someValue'),
    'Setter is not returning $this reference'
);

3 Comments

Using PHP 5.6, you could use the ::class static method, like this: $this->assertInstanceOf(ObjectToTest::class, $testedObj->setSomething('someValue')
Actually, the SomeClass::class feature was added in PHP 5.5
Yes, of course, but this is not a problem I guess. Services using php version 5.4 and lower are under 10% of total php usages (according to composer stats) seld.be/notes/php-versions-stats-2016-1-edition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.