3

Say I have this classes

class Grandpa
{
    public function call(){
        // Well, I want to know who calls me here
    }
}

class Father extends Grandpa
{
}

class GrandsonOne extends Father
{
}

class GrandsonTwo extends Father
{
}

Now, I call functions from the Grandson classes like so:

GrandsonOne::call();
GrandsonTwo::call();

How can I figure out who called?

tereško
  • 58,060
  • 25
  • 98
  • 150
Michael
  • 4,786
  • 11
  • 45
  • 68
  • 3
    I think your GradsonOne clss must extend to Father/Grandp. – Suresh Kamrushi Apr 01 '13 at 08:06
  • 3
    When you call someone you don't make them guess who's calling do you? You tell them. – vascowhite Apr 01 '13 at 08:06
  • 1
    This was one of the big pains I had to deal with when building a PHP ORM. I think the feature was on the roadmap, so maybe it exists now, but back then I just had to suck it up and add a `$subclass` parameter to the parent method, then override it on the child. It was bad, but it was the only option at the time… – Matchu Apr 01 '13 at 08:06
  • 1
    Probably the simplest way would be adding argument to call(), or overridden property, set in constructor, but maybe somebody knows better way? – Piotr Wadas Apr 01 '13 at 08:07
  • 2
    You might want to edit your question! At the moment you'll simply get a fatal error trying to call those functions – Suleman C Apr 01 '13 at 08:08
  • From logical point of view, sense of extend is, that no matter which GrandSon::preparesMeal() , it is always Grandpa::doesDishwash() . So what matters it makes who made dinner, if extending Grandpa means dishwash is same job anyway? – Piotr Wadas Apr 01 '13 at 08:16
  • Yes, indeed, I forgot to extend the Father. But you got the point.. Regarding one posible need for this is when you need some kind of overloading.. – Michael Apr 01 '13 at 08:23

1 Answers1

7

What you're looking for is the get_called_class function. From the PHP docs:-

Gets the name of the class the static method is called in.

So

class Grandpa
{
    public function call()
    {
        // Well, I want to know who calls me here
        echo get_called_class();
    }
}

will output the name of the called class.

Suleman C
  • 783
  • 4
  • 17