Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

ReflectionMethod

Inspect a method and invoke it on a compatible receiver.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

new ReflectionMethod($class, $method)

Inspect a method and invoke it on a compatible receiver. An instance method uses the provided object state, whereas a static method can be invoked with null. Passing null for an instance method raises ReflectionException. Use the two-argument constructor in PHP 8.4.

class Counter { public function __construct(private int $n){} public function plus(int $x): int{return $this->n+$x;} public static function unit(): int{return 1;} }
$r=new ReflectionMethod(Counter::class,"plus"); $s=new ReflectionMethod(Counter::class,"unit");
try{$r->invoke(null,3);}catch(ReflectionException $e){$bad=get_class($e);}
echo json_encode([$r->invoke(new Counter(4),3),$s->invoke(null),$bad]);
[7,1,"ReflectionException"]

Examples

<?php
class Counter { public function __construct(private int $n){} public function plus(int $x): int{return $this->n+$x;} public static function unit(): int{return 1;} }
$r=new ReflectionMethod(Counter::class,"plus"); $s=new ReflectionMethod(Counter::class,"unit");
try{$r->invoke(null,3);}catch(ReflectionException $e){$bad=get_class($e);}
echo json_encode([$r->invoke(new Counter(4),3),$s->invoke(null),$bad]);

Result

[7,1,"ReflectionException"]

Sources