Search code examples
phplate-static-binding

Which grandson called me?


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?


Solution

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