0

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?

6
  • AFAIK this is not possible no. If you are writing an if to determine multiple type you would need to start with the child class if ($foo instanceof ExampleClassExtension) { ... }elseif($foo instanceof ExampleClass) { ... } or use get_class Commented Jun 7, 2022 at 10:09
  • What is the use case whereby you want to know if it's the parent class specifically? Please edit the question to clarify, this sounds like an xyproblem.info Commented Jun 7, 2022 at 10:12
  • Does this answer your question? How do I get class name in PHP? - you can use something like get_class($b) === ExampleClass::class) with the code in the question. Commented Jun 7, 2022 at 10:17
  • @AD7six I don't want to check if its the parent class specifically, I want to check if it is a class specifically, regardless of inheritance. I want a child class to return false checking against the parent class rather than true as it currently does. Commented Jun 7, 2022 at 10:22
  • Thank you. I believe a combination of the above, using ExampleClass::class and order of if statements to be the correct solution. Commented Jun 7, 2022 at 10:24

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.