Anthop Posted April 27, 2009 Share Posted April 27, 2009 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 . Quote Link to comment https://forums.phpfreaks.com/topic/155774-oop-how-do-i-find-the-class-of-an-object/ Share on other sites More sharing options...
premiso Posted April 27, 2009 Share Posted April 27, 2009 echo __CLASS__; Do that inside of a class method and it should return to you what the class is. <?php class test { function __construct() { echo __CLASS__; } } $testClass = new test(); ?> Quote Link to comment https://forums.phpfreaks.com/topic/155774-oop-how-do-i-find-the-class-of-an-object/#findComment-819996 Share on other sites More sharing options...
Anthop Posted April 30, 2009 Author Share Posted April 30, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/155774-oop-how-do-i-find-the-class-of-an-object/#findComment-822985 Share on other sites More sharing options...
Mchl Posted April 30, 2009 Share Posted April 30, 2009 http://www.php.net/manual/en/ref.classobj.php Quote Link to comment https://forums.phpfreaks.com/topic/155774-oop-how-do-i-find-the-class-of-an-object/#findComment-822987 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.