Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Get class name of passed var?

I have a function that gets a class passed to it as a parameter. I would like to get the class name of the passed class as a string.

I tried putting this method in the passed class:

function getClassName()
    {
        return __CLASS__;
    }

but if the class is extended I assumed this would return the name of the subclass but it still returns the name of the super class which I find kind of odd.

So given a $var passed to a function as a parameter, is there a way to get a string of the class name?

Thanks!!

like image 430
JD Isaacks Avatar asked Nov 28 '22 11:11

JD Isaacks


2 Answers

See get_class, that should be exactly what you're trying to achieve.

$class_name = get_class($object);
like image 199
nortron Avatar answered Dec 18 '22 10:12

nortron


Simplest way how to get Class name without namespace is:

$class = explode('\\', get_called_class());
echo end($class);

Or with preg_replace

echo preg_replace('/.*([\w]+)$/U', '$1', get_called_class());
like image 27
OzzyCzech Avatar answered Dec 18 '22 10:12

OzzyCzech