0

I have a function which accepts no parameters, i.e. function doSomething(){...}.

If I run, call_user_func_array('doSomething', array('param1' => 'something')); it doesn't return an error.

Can I make it force an error like, "This function should not accept parameters".

2
  • Sure, just check via func_num_args() and throw an Exception if needed Commented Mar 7, 2015 at 16:27
  • BTW: It is completely irrelevant how you call the function, directly or with call_user_func() doesn't make a difference. Commented Mar 7, 2015 at 17:43

3 Answers 3

1

It's perfectly possible to send more parameters to a user-defined function than the function signature defines. That's because you can use additional code within your function to handle these, or simply ignore them.

function doSomething(){
    if (func_num_args() > 0) {
        throw new Exception('Too many arguments');
    }
    ....
}

Use something like the above to test the arguments that have been passed to your function

Sign up to request clarification or add additional context in comments.

7 Comments

I looked into this, but with a lot of functions it would be great not to have to do it for all all functions. Maybe I could check number of accepted arguments before calling call_user_func_array?
call_user_func_array('doSomething', array('param1' => 'something')); isn't conducive to checking the args in the array whenyou're defining the array in the actual call and not beforehand.... but why is it such an issue? If it's your code doing the call, then you control what gets passed to the function
I want to alert the user that the function does not accept parameters.
Is this a library that you're writing for others? If so, what's wrong with good documentation identifying the parameter arguments that can be passed, and the fact that any additional parameters will simply be ignored
Starting with PHP 5.6, I believe, functions can now actually declare explicitly that they take a variable number of arguments, making this stupid hack using func_get_args() obsolete. Just wanted to mention this small, related detail.
|
1

You could use func_num_args:

function foo()
{
    $n = func_num_args();
    if ($n > 0) {
        echo "Number of arguments: $n, 0 expected.";
    return;
    }
}

foo(1, 2, 3);

:: Info

Comments

0

Check out the ReflectionFunction class. Using that, you can detect how many parameters a function expects and avoid calling it on mismatch.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.