Eskinder
Eskinder

Reputation: 1409

How to check if a method exists and has arguments in 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)'))
{

}

Upvotes: 3

Views: 5342

Answers (2)

Alex Turpin
Alex Turpin

Reputation: 47776

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.

Upvotes: 11

Function overloading or method overloading is a feature that allows creating several methods with the same name which differ from each other in the type of the input and the output of the function. Unfortunately this is not implemented in php, you can not have two functions with the same name, using method overloading.

Why would you use the funcition_exists using function overloading?

Upvotes: 0

Related Questions