Dynamic method invocation
Learn to invoke a method at runtime with reflection.
Calling a method with invoke
Reflection does not only read; it also runs methods. ReflectionMethod::invoke($object, ...$args) calls a method from the outside.
For non-static methods $object is required; for static ones pass null. invokeArgs($object, $args) takes the parameters as an array.
This power sits at the heart of containers and event dispatchers: you take a method name from data and run it.
invokeArgs and newInstanceArgs
invokeArgs($object, [$a, $b]) shines when the parameter count varies. You build the array at runtime.
When constructing a class, ReflectionClass::newInstanceArgs($args) spreads the array into the constructor; newInstance() takes individual arguments.
That is how a dependency container reads constructor parameters via reflection and fills them with matching instances.
Exercise Call find with invoke
The UserService::find method is given. Build a ReflectionMethod instance and call find(42) via invoke(); print the result.
Show example solution
Build $rm = new ReflectionMethod("UserService", "find");. Call $result = $rm->invoke(new UserService(), 42);. Print with echo $result . "\n";.
Example solution:
<?php
class UserService {
public function find(int $id): string {
return "user-" . $id;
}
}
$rm = new ReflectionMethod("UserService", "find");
$result = $rm->invoke(new UserService(), 42);
echo $result . "\n";
Test yourself
-
Complete the invoke call
<?php $rm = new ReflectionMethod("UserService", "find"); $result = $rm->____(new UserService(), 42); echo $result . "\n";Show answer
<?php $rm = new ReflectionMethod("UserService", "find"); $result = $rm->invoke(new UserService(), 42); echo $result . "\n"; -
Match invoke concepts
- invoke
- Runs the method
- invokeArgs
- Runs with an array of parameters
- $object
- Target object (when non-static)
- null
- Target for a static method
-
What is the second parameter of invokeArgs?
- An array of parameters
- A single parameter value
- A class name string
- A ReflectionParameter object
Show answer
An array of parameters — Correct. invokeArgs takes parameters as an array.