3

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)'))
{

}
Eskinder
  • 1,369
  • 1
  • 14
  • 24

2 Answers2

11

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.

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
  • Thanks @AlexTurpin. i am creating an application using MVC guides and i am creating a controller which basically takes url address and instantiate a class accordingly and some of the classes has function and some of them has arguments to. So i wanted to check weather function exists and has arguments before i make the call. – Eskinder Apr 08 '14 at 22:03
  • @Eskinder then in that case I might suggest that you are using the wrong language if such strict checking is something you are worried about ;) And the best way to thank me, and others who've answered your questions before, would be to [accept an answer](http://meta.stackexchange.com/a/5235/158105) to your questions! – Alex Turpin Apr 08 '14 at 22:05
0

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?