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 use of undefined constant User - assumed 'User'.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

3 Answers3

149

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

I think you are using this function wrong. Try:

$this->assertInstanceOf('User', $user);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Mantas
  • 4,259
  • 2
  • 27
  • 32
  • 62
    As of [PHP 5.5](http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name) you can use this syntax as well `$this->assertInstanceOf(User::class, $user);`. – james2doyle Jun 05 '16 at 23:56
65

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);
Rápli András
  • 3,869
  • 1
  • 35
  • 55
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'
);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rafal Kozlowski
  • 720
  • 5
  • 12
  • 3
    Using PHP 5.6, you could use the `::class` static method, like this: `$this->assertInstanceOf(ObjectToTest::class, $testedObj->setSomething('someValue')` – marcegarba Dec 09 '15 at 18:41
  • 2
    Actually, the `SomeClass::class` feature was added in [PHP 5.5](http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name) – james2doyle Jun 05 '16 at 23:57
  • 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) https://seld.be/notes/php-versions-stats-2016-1-edition – Rafal Kozlowski Jun 07 '16 at 07:14