3

In this situation:

$callable1 = "\somenamespace\someclass::somefunction";
$callable2 = array('someclass', 'somefunction');
$callable3 = 'somefunction';
$callable4 = array($someInstance, 'somefunction');

Is there a way I can reliably extract the namespace and class (if any) from a callable, no matter the format in which it is defined?

KrekkieD
  • 967
  • 9
  • 23
  • Are you wanting the function to tell you the namespace and class? – Machavity Jun 28 '14 at 14:25
  • I want something like `$class = getClassFromCallable($callable);` and want `$class` to be `someclass` – KrekkieD Jun 28 '14 at 14:28
  • @Greggg what if the callable is an anonymous function? – ggioffreda Jun 28 '14 at 14:41
  • Just null would be fine then, or false. – KrekkieD Jun 28 '14 at 14:44
  • @mpapec that doesn't work, `get_class` expects an object not a callable. – KrekkieD Jun 28 '14 at 14:45
  • Do you mean pass in one of your four variables and it determines what the class name is given it's format (and data)? – Jared Farrish Jun 28 '14 at 14:49
  • @JaredFarrish yes :) so results for 1 through 4 (for getting class) would be: 1; `someclass`, 2; `someclass`, 3; `null` or `false` (as `get_class()` returns `false` this would probably be better, and 4; an identical response as `get_class($someInstance)` – KrekkieD Jun 28 '14 at 14:52
  • 1
    Why don't you just write a function to parse your examples based on their format? – Jared Farrish Jun 28 '14 at 14:55
  • well, yes, that could work, but I was hoping there'd be a way without manual interpretation of the callable. The callable itself is pretty much a direct pointer to something, which could be backtraced to return partial information (function name, class name, namespaces). – KrekkieD Jun 28 '14 at 15:04
  • Create a `ReflectionFunction`, then `getClosureScopeClass`... https://www.php.net/manual/en/class.reflectionfunction.php – jave.web Aug 16 '23 at 22:52

1 Answers1

2

The following class seems to do exactly what you need:

CallableReflection.php

It looks like the namespace extraction is missing. You can add it yourself with PHP's reflection:

ReflectionClass::getNamespaceName

bitWorking
  • 12,485
  • 1
  • 32
  • 38
  • Just gave this a try, it returns the class with the namespace, which actually isn't bad for what I'm intending to use it for. Quite a class though! Guess my request was harder than I anticipated. Cool, thanks. :) – KrekkieD Jun 28 '14 at 15:05
  • If the answer works for you, please be so kind and accept it. So it's no longer in the list of unanswered questions. – bitWorking Jun 28 '14 at 15:15
  • Fine, I don't say this because it's my answer ;) Many new users don't know how this site works. But I see, you're not really new.. – bitWorking Jun 28 '14 at 15:49