Home > Net >  Is there any way to find argument type list of a function in php?
Is there any way to find argument type list of a function in php?

Time:12-19

For example, look at this php code:

class AuthController extends Controller {
   public function store(LoginRequest $request, int $id) {
      // code...
   }
}

And I wanna get the argument type list for the method AuthController::store().

For example, doing this:

print_r(get_arg_types('AuthController::store'));

should return:

Array (
   [0] => LoginRequest
   [1] => int
)

Now, this get_arg_types() doesn't exist yet, but I want to create & use that. Is there an way?

CodePudding user response:

First reflect the class, then the method, then the parameters.

<?php

class Controller {}

class AuthController extends Controller {
   public function store(LoginRequest $request, int $id) {
      // code...
   }
}

$ref = new ReflectionClass('AuthController');
$methods = $ref->getMethods();
$params = $methods[0]->getParameters();
foreach ($params as $param)
var_dump($param->getType()->getName());

Output

string(12) "LoginRequest"
string(3) "int"

Teh Playground!

CodePudding user response:

Yes, what you're looking for is called Reflection, and php has a whole range of functions to do such things.

Most likely this will get you on your way: ReflectionMethod. and here is some more generic background info.

  • Related