Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP How to get a method name with a class and namespace path as a string?

I really hate to write this question because I'm kind-of "research guy" and, well, I always find what I'm searching for... But this one bugs me a lot and I can't find the answer anywhere... So, here it goes:

As the title says I need to get a method name with the trailing class and namespace path as a string. I mean something like this: "System\Language\Text::loadLanguageCache". As we know, you can get a class name (with full namespace path) by typing, i.e.: Text::class and it returns "System\Language\Text", but is there a way to get this for a method? Something like: Text::loadLanguageCache::function to get string: "System\Language\Text::loadLanguageCache"?

Edit:

I think I should explain this further... I know about magic constant __METHOD__ but the problem is that it works inside the called method and I need this "outside the method". Take this as example:

//in System\Helpers
function someFunction()
{ return __METHOD__; }

That's all OK with this if I call the function I'll get (let's assume that method is in System\Helpers class) - "System\Helpers::someFunction". But what I want is this:

//in System\Helpers
function someFunction()
{ //some code... whatever }

// somewhere not in System\Helpers
function otherFunction()
{
    $thatFunctionName = Helpers::someFunction::method //That imaginary thing I want

    $thatClassName = Helpers::class; //this returns "System\Helpers"
}

I hope this cleared my question a bit :)

like image 524
Vytautas Lozickas Avatar asked Nov 30 '13 15:11

Vytautas Lozickas


1 Answers

You must use the magic constant, you can read more about at Magic constants in php.net

__METHOD__

Outside of the class you must use Reflection as is explained at ReflectionClass documentation:

<?php
$class = new ReflectionClass('ReflectionClass');
$method = $class->getMethod('getMethod');
var_dump($method);
?>;

Returns:

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(9) "getMethod"
  ["class"]=>
  string(15) "ReflectionClass"
}
like image 113
mcuadros Avatar answered Oct 31 '22 00:10

mcuadros