58

I can check all available methods for an object like so:

$methods = get_class_methods($object);

But how can I see which arguments have to be sent to these methods?

Is there a function for this?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Rakward
  • 1,657
  • 2
  • 18
  • 24

1 Answers1

123

You can use reflection...

$r = new ReflectionMethod($className, $methodName);
$params = $r->getParameters();
foreach ($params as $param) {
    //$param is an instance of ReflectionParameter
    echo $param->getName();
    echo $param->isOptional();
}
ircmaxell
  • 163,128
  • 34
  • 264
  • 314
  • 4
    And when you just want to know how many arguments a required, use `getNumberOfRequiredParameters` http://www.php.net/manual/en/reflectionfunctionabstract.getnumberofrequiredparameters.php – bastey Sep 02 '13 at 14:53
  • 1
    Is there anyway to return what would be accepted as an argument successfully? For example, if it accepts a string, list the strings that is accepts? – Greg L Mar 10 '14 at 17:28
  • @GregL: the engine has no concept of "list the strings that it accepts". Specifically, there's no way to tell the engine that it should accept a string in the first place. You can only hint on Arrays, Objects (via class name) and Callbacks (callable hint). – ircmaxell Mar 10 '14 at 17:58
  • You could try to parse PHPDoc, it's not easy and your team would have to agree on a format for declaring "accepted strings". Example: http://gonzalo123.com/2011/04/04/reflection-over-phpdoc-with-php/ – carlosvini Mar 03 '15 at 18:25
  • If using something like PHPStorm, rather than commenting, you can type-hint the for loop to make it a bit easier to tinker with: `foreach ($params as /** @var \ReflectionParameter */ $param)` – Dave Stewart Feb 25 '16 at 12:14
  • 2
    Just to be 110%...no, 120% clear -- @AngelS.Moreno was being sarcastic. I won't deny the rare occasion that the information illuminated by reflection is useful, but for 99.999% of industry-worthy code that won't get you crucified in code review meetings, reflection has no place whatsoever. – Luke A. Leber Oct 05 '16 at 00:53
  • I don't remember where my head was 4 years ago, but I like reflection. I don't think I was being sarcastic. However, I agree with @LukeA.Leber I never use reflection in production. I use it for writing tests and command line utils. – Angel S. Moreno Oct 05 '16 at 01:22
  • I /am/ needing to use reflection for an MVC framework I'm building in PHP so it does have a place in production, just in very specific instances. It can also be implemented to check your code before accepting it into an versioning repository to implement business-specific rules (no arrays in parameters, for example) – whiskeyfur Nov 13 '17 at 17:13