4

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!!

JD Isaacks
  • 56,088
  • 93
  • 276
  • 422

6 Answers6

12

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

$class_name = get_class($object);
nortron
  • 3,873
  • 1
  • 24
  • 27
11

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());
OzzyCzech
  • 9,713
  • 3
  • 50
  • 34
1

__ CLASS __ with return the name of the class the method is implemented in.

If you want to get the class name of an object passed then you can use:

get_class($param);

Also, if you're using PHP5 then the Reflection classes provided are also useful.

Neel
  • 854
  • 5
  • 7
0

Use get_class:

$className = get_class($object);
Victor Nicollet
  • 24,361
  • 4
  • 58
  • 89
0

Straight from the php docs: http://uk.php.net/manual/en/function.get-class.php

<?php

abstract class bar {
    public function __construct()
    {
        var_dump(get_class($this));
        var_dump(get_class());
    }
}

class foo extends bar {
}

new foo;

?>

The above example will output:

string(3) "foo"
string(3) "bar"
Rufinus
  • 29,200
  • 6
  • 68
  • 84
0

you could also add a method into the passed class(es) returning this:

var_dump(get_called_class());

jellyfishtree
  • 1,811
  • 1
  • 10
  • 11