KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / PHP

ReflectionMethod

Inspecteert een methode en roept haar aan op een passend object.

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

Syntax

new ReflectionMethod($class, $method)

Inspecteert een methode en roept haar aan op een passend object. Een instantiemethode gebruikt de objecttoestand, een statische methode accepteert null. Bij een instantiemethode veroorzaakt null ReflectionException. Gebruik in PHP 8.4 de constructor met twee argumenten.

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"]

Voorbeelden

<?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]);

Resultaat

[7,1,"ReflectionException"]

Bronnen