6

I have a PHP function that requires can take 3 parameteres... I want to pass it a value for the 1st and 3rd parameters but I want the 2nd one to default...

How can I specify which ones I am passing, otherwise its interpreted as me passing values for the 1st and 2nd slots.

Thanks.

4 Answers 4

9

You cannot "not pass" a parameter that's not at the end of the parameters list :

  • if you want to specify the 3rd parameter, you have to pass the 1st and 2nd ones
  • if you want to specify the 2nd parameter, you have to pass the 1st one -- but the 3rd can be left out, if optionnal.

In your case, you have to pass a value for the 2nd parameter -- the default one, ideally ; which, yes, requires your to know that default value.


A possible alternative would be not have your function take 3 parameters, but only one, an array :

function my_function(array $params = array()) {
    // if set, use $params['first']
    // if set, use $params['third']
    // ...
}

And call that function like this :

my_function(array(
    'first' => 'plop',
    'third' => 'glop'
));

This would allow you to :

  • accept any number of parameters
  • all of which could be optionnal

But :

  • your code would be less easy to understand, and the documentation would be less useful : no named parameters
  • your IDE would not be able to give you hints on which parameters the function accepts
Sign up to request clarification or add additional context in comments.

2 Comments

Yep, I know ^^ That's why optionnal parameters should be at the right of the parameters list, and not in the middle ;-) (but yes, if 2nd and 3rd parameters are both optionnal...)
you could factor this with some clever uses of some php functions, but the ends seldom justify the means, see: php.net/manual/en/function.func-get-args.php
1

Once you've defined a default parameter, all the parameters after that one cannot be required. You could do something like:

const MY_FUNCTION_DEFAULT = "default";

public function myFunction($one, $two = "default", $three = 3)
{
   if (is_null($two)) $two = self::MY_FUNCTION_DEFAULT;
   //...
}

// call
$this->myFunction(1, null, 3);

You might also define an empty parameter set and use func_get_args to pull in parameters and analyze those using instanceof or typeof/gettype for type checking if your function is simple enough.

1 Comment

and I post similar answers. he gets a vote up, i get voted down. how does that work?
1

You could use ReflectionFunction. This problem has already been solved by an anonymous contributor at php.net, see orinal here: http://www.php.net/manual/en/function.call-user-func-array.php#66121

For those wishing to implement call-by-name functionality in PHP, such as implemented e.g. in DB apis, here's a quick-n-dirty version for PHP 5 and up

function call_user_func_named($function, $params)
{
    // make sure we do not throw exception if function not found: raise error instead...
    // (oh boy, we do like php 4 better than 5, don't we...)
    if (!function_exists($function))
    {
        trigger_error('call to unexisting function '.$function, E_USER_ERROR);
        return NULL;
    }
    $reflect = new ReflectionFunction($function);
    $real_params = array();
    foreach ($reflect->getParameters() as $i => $param)
    {
        $pname = $param->getName();
        if ($param->isPassedByReference())
        {
            /// @todo shall we raise some warning?
        }
        if (array_key_exists($pname, $params))
        {
            $real_params[] = $params[$pname];
        }
        else if ($param->isDefaultValueAvailable()) {
            $real_params[] = $param->getDefaultValue();
        }
        else
        {
            // missing required parameter: mark an error and exit
            //return new Exception('call to '.$function.' missing parameter nr. '.$i+1);
            trigger_error(sprintf('call to %s missing parameter nr. %d', $function, $i+1), E_USER_ERROR);
            return NULL;
        }
    }
    return call_user_func_array($function, $real_params);
}

Comments

-3
function ($foo, $mate, $bar = "") {
  // ... some code
}

2 Comments

because you can't have a required parameter after an optional one.
also, this does not answer the question about passing specific variables to specific parameters, it only shows how to create a function with parameters, one of which has a default making it optional

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.