Home » Php » PHP: instanceof equivalent for a string-represented classname

PHP: instanceof equivalent for a string-represented classname

Posted by: admin April 23, 2020 Leave a comment

Questions:

It’s best to explain by an example.
I look for a function “theFunctionILookFor” that will make the code work.

$myClassName = "someName";
$parentOrInterfaceName = "someParent";
if ( theFunctionILookFor ($myClassName))  echo "is parrent";

edit: I try to avoid instantiating the class just to perform this check. I would like to be able to pass 2 string parameters to the checking function

How to&Answers:

Looks like this is my answer: is_subclass_of

It can accept both parameters as strings

http://php.net/manual/en/function.is-subclass-of.php

Answer:

Try is_subclass_of(). It can accept both parameters as strings. http://php.net/manual/en/function.is-subclass-of.php

Answer:

I think that instanceof is a lot faster and more clear to read.

instanceof does not work on strings, because it can be used as a “identifier” for a class:

 $temp = 'tester';
 $object  = new sub();
 var_dump($object instanceof $temp); //prints "true" on php 5.3.8

 class tester{}

 class sub extends \tester{

 }

Also, it works on interfaces – you just need a variable to contain the absolute class name (including namespace, if you want to be 100% sure).

Answer:

Using the Reflection API, you can construct a ReflectionClass object using the name of the class as well as an object.

Answer:

You might use this?

http://www.php.net/manual/en/function.get-parent-class.php

From the page:

get_parent_class

(PHP 4, PHP 5, PHP 7)
get_parent_class — Retrieves the parent class
name for object or class

Description

string get_parent_class ([ mixed $object ] )

Retrieves the parent
class name for object or class.

Answer:

This is an old thread, but still for future reference, you can use the functions is_a and is_subclass_of to accomplish this in a more efficient way.
No need to instantiate anything, you can just pass your string like:

if (is_subclass_of($myObject, 'SomeClass')) // is_a(...)
  echo "yes, $myObject is a subclass of SomeClass\n";
else
  echo "no, $myObject is not a subclass of SomeClass\n";

PHP Docs:

http://www.php.net/manual/en/function.is-a.php
http://www.php.net/manual/en/function.is-subclass-of.php