CodeBlanks Logo Icon CodeBlanks

ReflectionMethod

PHP course · Expert · Lesson 17/54

Learn a method's parameters, visibility and return type with ReflectionMethod.

Inspect a method with ReflectionMethod

ReflectionMethod inspects a single method. new ReflectionMethod("UserService", "find") gives you the find method.

getParameters() returns a ReflectionParameter for each parameter; getName() returns the parameter name. isPublic(), isPrivate(), isProtected() describe visibility, getReturnType() the return type.

You can therefore use a third-party class without docs: parameter names and types are right there.

Inspect a parameter with ReflectionParameter

Each ReflectionParameter mirrors one parameter. getName() returns the name, getType() the type, isOptional() whether it is optional.

Optional parameters expose their default via getDefaultValue(); but first check isDefaultValueAvailable() to avoid surprises.

With this data, for example, a CLI tool can build options from parameter names.

Exercise Print the find method's parameters

The UserService::find method is given. Build a ReflectionMethod instance and print each parameter's name on a separate line using getParameters().

Show example solution
Build $rm = new ReflectionMethod("UserService", "find");. Print with foreach ($rm->getParameters() as $param) { echo $param->getName() . "\n"; }.
Example solution:
<?php
class UserService {
    public function find(int $id, ?string $field = null): ?array {
        return null;
    }
}

$rm = new ReflectionMethod("UserService", "find");
foreach ($rm->getParameters() as $param) {
    echo $param->getName() . "\n";
}

Test yourself

  1. Match ReflectionMethod methods

    getParameters
    Returns the parameter list
    isPrivate
    Asks whether it is private
    getReturnType
    Returns the return type
    getName
    Returns the method name
  2. What does new ReflectionMethod("UserService", "find") return?

    • All methods of the UserService class
    • All parameters of the find method
    • A ReflectionMethod object representing find
    • The return type of the find method
    Show answer

    A ReflectionMethod object representing find — Correct. You get a ReflectionMethod for that single method.

  3. Loop with getParameters()

    <?php
    $rm = new ReflectionMethod("UserService", "find");
    foreach ($rm->____() as $param) {
        echo $param->getName() . "\n";
    }
    
    Show answer
    <?php
    $rm = new ReflectionMethod("UserService", "find");
    foreach ($rm->getParameters() as $param) {
        echo $param->getName() . "\n";
    }
    

All lessons in Expert