Получить тип аргументов метода класса - PullRequest
1 голос
/ 30 марта 2019

Я читаю о php ReflectionFunction. Можно ли использовать его для проверки типа различных аргументов метода класса?

1 Ответ

1 голос
/ 30 марта 2019

Вы должны использовать класс ReflectionMethod вместо ReflectionFunction:

class Test {
    public function Test1(int $number, string $str) {  }
}

//get the information about a specific method.
$rm = new ReflectionMethod('Test', 'Test1');

//get all parameter names and parameter types of the method.
foreach ($rm->getParameters() as $parameter) {
    echo 'Name: '.$parameter->getName().' - Type: '.$parameter->getType()."\n";
}

демо: https://ideone.com/uBUghi


Вы можете использовать следующее решение для получения всех параметров всех методов, используя ReflectionClass:

class Test {
    public function Test1(int $number, string $str) {  }
    public function Test2(bool $boolean) {  }
    public function Test3($value) {  }
}

//get the information of the class.
$rf = new ReflectionClass('Test');

//run through all methods.
foreach ($rf->getMethods() as $method) {
    echo $method->name."\n";

    //run through all parameters of the method.
    foreach ($method->getParameters() as $parameter) {
        echo "\t".'Name: '.$parameter->getName().' - Type: '.$parameter->getType()."\n";
    }
}

demo: https://ideone.com/Ac7M2L

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...