Home > Software design >  PHP get params from function inside of Namespace
PHP get params from function inside of Namespace

Time:04-11

I'm trying to get the params (names) of a function that is stored within a namespace and class. I've tried ReflectionFunction, but I can only make that work without namespaces and classes. The function I'm trying to call is non-static, which doesn't make it much easier.

namespace app\http;

class Test {
   public function func(User $user, $id) {
     return $user;
   } 
}

I'm trying to get "user" and "id" from here. Does someone have a suggestion?

CodePudding user response:

Using: https://www.php.net/manual/en/reflectionfunctionabstract.getparameters.php

$ref = new ReflectionMethod(\app\http\Test::class, "func");

foreach ($ref->getParameters() as $param) {
    echo $param->getName();
}

$ref->getParameters() returns an array of ReflectionParameter classes which allows you to get more information than just the name; https://www.php.net/manual/en/class.reflectionparameter.php

You could also use the string value for the class: "\app\http\Test" but the special ::class constant is more reliable when in different namespaces (if not using the fully qualified name).

The special ::class constant allows for fully qualified class name resolution at compile time, this is useful for namespaced classes

  • Related