Jump to content

OOP: How do I find the class of an object?


Anthop

Recommended Posts

While I'm familiar with object-oriented programing, in Java and other languages, I'm not sure how to do this simple task in PHP:

 

If I have an instance of some object, how do I find out what its class is (perhaps returned to me as a string)?

 

Also, I know PHP isn't strongly typed, but is there some way to "sanity check" in my code that an object is an instance of class X or a subclass of X?

 

Thanks in advance for your time :).

Thanks for the reply, premiso, and sorry for my own late reply. :-[

 

The echo __CLASS__ works fine when its within the code for the class I'm trying to discover, but it isn't really the general solution that I'm looking for.  For example, see the following code:

 

interface Classable {

public function getClass();
}

class Test implements Classable {

public function getClass() {
	return __CLASS__;
}
}

class SubTest extends Test {}

$o = new Test();
echo($o->getClass() . "\n");  // Returns "Test".

$o = new SubTest();
echo($o->getClass() . "\n");  // Returns "Test".

 

First of all, it limits me to finding the class of objects which implement the Classable interface.

 

Secondly, I can't just define the function once and cause it to work correctly for all subsequent sub-classes, as the function returns the name of the class in which the function was last defined.  That means, I have to trust that every sub-class has a correct implementation of the Classable interface.

 

I'll think about this a bit more, but for now, I'm going to assume that this is just how it is going to be.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.