开发者

Get object class name from within parent class?

开发者 https://www.devze.com 2023-01-15 09:01 出处:网络
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:

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 $char开发者_开发技巧One 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?


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";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号