get class name for an object.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
djunk2
Forum Newbie
Posts: 3
Joined: Thu Jan 15, 2004 3:32 pm

get class name for an object.

Post 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);
		};
	}
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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'
djunk2
Forum Newbie
Posts: 3
Joined: Thu Jan 15, 2004 3:32 pm

Post 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
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Also (php manual notes):
As of PHP 4.3.0 the constant __CLASS__ exists and contains the class name.
Post Reply