0

I'm trying to get the name of the method from the child class that called my method in the base class. How can I go about getting this?

class MyBaseClass {
    protected static function mybasemethod() {
        // how can I get the name of the method that called this?
        // I'm looking for 'myothermethod'
    }
}


class MyClassA extends MyBaseClass {
   protected static function myothermethod() {
       self::mybasemethod();
   }
}
user391986
  • 29,536
  • 39
  • 126
  • 205
  • you need the name of methods inside child class,right? – Lal krishnan S L Jun 11 '15 at 04:43
  • possible duplicate of [How to get name of calling function/method in PHP?](http://stackoverflow.com/questions/2110732/how-to-get-name-of-calling-function-method-in-php) – scrowler Jun 11 '15 at 04:43
  • Yes, i'm trying to get some unique information about what's calling the method in the base class (for caching purposes I'm going to use it as part of a caching key). So in the base class method I want to get the name of the method in the child class that called it so in htis case it wold be 'myothermethod' – user391986 Jun 11 '15 at 04:44
  • Suggest you've got some typos in your example. You'd be looking for "myothermethod" not "mybasemethod", and `myothermethod()` would be calling `self::mymethod` not `mybasemethod()`? – scrowler Jun 11 '15 at 04:44
  • http://php.net/manual/en/function.get-class-methods.php – Lal krishnan S L Jun 11 '15 at 04:45

2 Answers2

0

To get the name of classes you can try the function get_class_methods() To know more use this link

<?php

class myclass {
    // constructor
    function myclass()
    {
        return(true);
    }

    // method 1
    function myfunc1()
    {
        return(true);
    }

    // method 2
    function myfunc2()
    {
        return(true);
    }
}

$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());

foreach ($class_methods as $method_name) {
    echo "$method_name\n";
}

?>
Lal krishnan S L
  • 1,684
  • 1
  • 16
  • 32
-1

Thank you for inspiring today's learning opportunity. I have often idly wondered whether this could be done, but never bothered to investigate. Now, I know that it can, indeed, be done!

I tested the following code fragment in a routine that I am currently testing.

System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace ( false );
System.Diagnostics.StackFrame frame = trace.GetFrame ( 1 );
Console.WriteLine ( "Calling method = {0}" , frame.GetMethod ( ).Name );

The output is as follows.

Calling method = UtilsExercises

UtilsExercises is the name of the method that called the routine into which I embedded the code.

The preceding example is an adaptation of the sample shown in the StackTrace Class documentation at https://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace(v=vs.110).aspx.

David A. Gray
  • 1,039
  • 12
  • 19