SamuraiMelon
SamuraiMelon

Reputation: 367

InstanceOf Object Inheritance

Is it possible to determine whether an object is of a specific class, rather than whether an object is a parent class or that class? i.e. only return true if its that specific class, and false if it is the parent class.

For example:

class ExampleClass {
    ...
}

class ExampleClassExtension extends ExampleClass {
    ...
}

$a = new ExampleClass();
$b = new ExampleClassExtension();

var_dump($b instanceof ExampleClass) //Returns true as ExampleClassExtension is inherited from ExampleClass although I would like it to return false.

Is there any way to ignore the inheritance and check whether an object is specifically that class and return false if it is the parent class or child class or just any class that isn't the specific class I'm checking for?

Upvotes: 0

Views: 493

Answers (1)

MoròSwitie
MoròSwitie

Reputation: 1516

If you want to specifically check if a class is equal to a certain class, you can use reflection

<?php

class ExampleClass {
    public const A = 'a';
}

class ExampleClassExtension extends ExampleClass {
    public const B = 'b';
}

$a = new ExampleClass();
$b = new ExampleClassExtension();

$reflectionClass = new ReflectionClass($b);
var_dump($reflectionClass->getName() === ExampleClass::class);

Upvotes: 1

Related Questions