Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have function that has three parameters, called key, value and attribute.

Parameter attribute may be empty or have within two arguments. Code of function below is shortened (deprived of arguments validation)

public function Set_ContentUsage($Key, $Value, $Attribute=NULL)
{
    $this -> ContentUsage = array();
    $Attribute = array_slice(func_get_args(), 2);

    /* validation of arguments */

    $this -> ContentUsage['key'] = $Key;
    $this -> ContentUsage['value'] = $Value;


    if(count($Attribute) == 1)
    {
        $this -> ContentUsage['keyattr'] = ($Key == MarC::MARC_OPTION_ATTRVAL) ? $Attribute[0] : FALSE;
        $this -> ContentUsage['valueattr'] = ($Value == MarC::MARC_OPTION_ATTRVAL) ? $Attribute[0] : FALSE;
    }
    else
    {
        $this -> ContentUsage['keyattr'] = $Attribute[0];
        $this -> ContentUsage['valueattr'] = $Attribute[1];
    }
}

My question is how to get multiple arguments for last parameter in better way? in cases like this.

share|improve this question
3  
I don't understand what you're asking. – Robert Harvey Mar 25 at 21:31
up vote 1 down vote accepted

The question is a bit unclear, but I'll assume you're referring to the use of array_slice(func_get_args(), 2); to implement what I'm used to calling a "rest parameter", which results in a very misleading function signature.

The simplest and cleanest alternative is to use the ... operator added in PHP 5.6.

public function Set_ContentUsage($Key, $Value, ...$Attribute) {
    $firstAttribute = $Attribute[0];
    ...
}

This makes it immediately obvious to anyone reading your code that the last parameter is meant to be an array of all remaining arguments.

If this is not an option, then you'll simply have to change this function's call sites to pass an actual array for the third argument, or stick to func_get_args() until you can upgrade to 5.6.

share|improve this answer
    
Explanation on PHP.net is written very uncleary, but I suppose that with PHP 5.6 instead func_get_args() I need only to use something like $NameOfParam[$Index] to get nth argument. Please, (if I am right in this), write this into your answer and I will accept it. – Václav 2 days ago
    
@Václav Added that to the sample code snippet – Ixrec 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.