Home > Mobile >  Using chosen methods with Reflection class
Using chosen methods with Reflection class

Time:12-05

In my class i have some final methods than i need to using them in another method by dynamic(if any method added, the master method Should not change),

I use Reflection class for get the methods:


$shop_id = $shop_id ? $shop_id : $this->shop_id;
$shop = Shop::whereId($shop_id)->first();
$total_rating = 0;
$averageRatingCalculator = new AverageRatingCalculator($shop_id);
$reflection_class = new ReflectionClass($averageRatingCalculator);
$final_class_methods = $reflection_class->getMethods(ReflectionMethod::IS_FINAL);
foreach($final_class_methods as $method){
    $method_name = $method->name;
    $total_rating  = $this->$method_name();
}

this code works well and has no problems.

Question: i want to use Reflection instead $this->, how i must use Reflection::invoke() here?

CodePudding user response:

Haven't tried this, but something like

$total_rating  = $method->invoke($this);

So $method is the reflection method object from your loop (and the result of getMethods) and you pass in the object which you want to invoke the method on.

(from example on manual page https://www.php.net/manual/en/reflectionmethod.invoke.php#refsect1-reflectionmethod.invoke-examples)

  • Related