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 improve this function to get multiple arguments for parameter $Attribute
without $Attribute = array_slice(func_get_args(), 2);
?
I found that if I only delete
$Attribute = array_slice(func_get_args(), 2);
it leads to malfunction of rest code.
1
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.
2