Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a method exists and has arguments in PHP

Tags:

php

I want to check if a method exists and has arguments. Here is some snippet.

// this only checks if the function exist or not
if(method_exists($controller, 'function_name')) 
{
  //do some stuff
}

But what i want to do is

if(method_exists($controller, 'function_name(with_args)'))
{

}
like image 207
Eskinder Avatar asked Jan 22 '26 15:01

Eskinder


1 Answers

You can use ReflectionMethod's getParameters to get a list of parameters for a method. You could then check the length of that list or do any other operations you need on the parameters.

<?php
    class Foo {
        function bar($a, $b, $c) {
            return $a + $b + $c;
        }
    }

    $method = new ReflectionMethod('Foo', 'bar');
    var_dump($method->getParameters());
?>

I don't know what you would be using this for but I would advise against using reflection casually. You could probably rethink your way of doing things.

like image 100
Alex Turpin Avatar answered Jan 24 '26 07:01

Alex Turpin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!