views:

19

answers:

1

I am wanting to use the get_class($var) to show the class of an object. What would be the best way to do this? My code at the moment is:

abstract class userCharacter {

    var $cName;
    var $cLevel = 0;
    var $cHP = 50;
    var $cMP = 20;

    function __construct($n) {
        $this->cName = $n;
    }

    function showDetails() {
        echo $this->cName . "<br />";
        echo "Level: " . $this->cLevel . "<br />";
        echo "HP: " . $this->cHP . "<br />";
        echo "MP: " . $this->cMP . "<br />";
    }
} // userCharacter

class warrior extends userCharacter {
} // warrior

And I create the object with:

$charOne = new warrior($name);

What I'm wanting to do is in the showDetails() function of the userCharacter class have a line similar to:

echo "Class: " . get_class($charOne) . "<br />";

But, I'm pretty sure that this won't work because the $charOne variable isn't in the right scope.

I'm thinking that I would need to declare $charOne with something like:

global $charOne = new warrior($name);

Would this work? If not, what is the best way to do this, if possible at all?

+1  A: 

You want

echo get_class($this) ; 

At runtime, the actual class will be figured out. That's what is cool about polymorphism.

However, even better, you want to do something like this:

echo $this->getClassDisplayName();

Then write that function for each subclass.

Or, the base class can have this type of function:

function getClassDisplayName()
{
    return ($this->classDisplayName == "" ? getClass($this) : $this->classDisplayName );
}

Then in the constructor of your subclasses:

public __construct()
{
    $this->classDisplayName = "The Mighty Warriors of Azgoth";
}
Zak
Oooh, yeah, that is cool. Thanks for the answer. The more I play with OOP the more I love it!
Saladin Akara