Reputation: 49
This question is difficult to ask, as it seems to answer.
I have a method declared in abstract class parent{}
, that gets echoed in child class foo{}
This method requires the current current class name i.e. foo
to work, So how do I get this name without passing it through the argumet?
abstract class parent{
public function init(){
echo "I am running from class ....";
// I want this to say, that is it running from any class that is extending it.
}
}
This is the child class, and is only supposed to hold one username;
class foo extends parent{
echo $this->init();
// I could pass the class name through the argument, but I am looking for other alternatives
}
Upvotes: 1
Views: 42
Reputation: 15053
echo "I am running from class " . get_class($this);
__CLASS__
is the declaring class (the class you're using it in) and get_class
will get the concrete class of the provided object. So get_class($this)
will return the same value as __CLASS__
or one of its child classes.
Upvotes: 5
Reputation: 6896
@sroes has the answer, but your code example could be something like:
abstract class parentclass{
public function init(){
echo "I am running from class ....";
echo __CLASS__;
echo ' But I am ' . get_class($this);
}
}
class foo extends parentclass{
}
$f = new foo();
$f->init();
Shows diff between const CLASS and get_class()
Upvotes: 1