Page 1 of 1

get class name for an object.

Posted: Thu Jan 15, 2004 3:32 pm
by djunk2
Hi

Is there a function to return the name of the class an object is an instantiation of?

eg

Code: Select all

$someVar = new myObj();
is there a function such as

Code: Select all

objectType ($someVar);
that would return "myObj" ???

Ive written one which works fine which relies on the [php_man]var_export[/php_man] function, which ive included below - but I was looking for something a bit better if poss - I'm not sure this is the best way to do it. surely there must be a built in function for doing this


here's what I have:

========================

Code: Select all

function getObjectType($object) {
		// returns the class name of an object
		if (is_object($object)) {
			$objString = var_export($object, TRUE);
			$spaceA = strpos($objString, " ", 0);
			$spaceB = strpos ($objString, " ", $spaceA+1);
			return substr($objString, $spaceA, $spaceB - $spaceA);
		};
	}

Posted: Thu Jan 15, 2004 4:17 pm
by markl999
get_class sounds like what you want.
E.g.

Code: Select all

class Foo {
  function Foo(){
  }
}
$bar =& new Foo();
echo get_class($bar); //outputs 'foo'

Posted: Thu Jan 15, 2004 6:07 pm
by djunk2
oh. makes sense really - trust me to come up with some convoluted method - but i couldn't find that function when i was looking!

thanks

Posted: Thu Jan 15, 2004 6:11 pm
by McGruff
Also (php manual notes):
As of PHP 4.3.0 the constant __CLASS__ exists and contains the class name.