Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.