2
public function setSomething($what){
  $this->something = $what;
}

...

$obj->setSomething(array('aaa', 'bbb', 'ccc'));

or

public function setSomething(){
  $this->something = array_values(func_get_args());
}

...

$obj->setSomething('aaa', 'bbb', 'ccc');

Which method would you use and why?

ps: the second one could also be used to emulate keys I think, if you give out argument names:

$obj->setSomething($key1 = 'aaa', $key = 'bbb', $key = 'ccc');
2
  • How are you getting the data that you're passing to the setter? Commented Jul 6, 2011 at 21:46
  • In general, use a function signature that conveys your API to the developer Commented Jul 6, 2011 at 22:20

1 Answer 1

2

I usually only use an array if multiple arguments are optional. For example, if I have a report that can take a company ID, an employee ID, or both. I won't have function report ($CompanyID = null, $EmployeeID = null), I'll do function report($array) and then inside the function, do if (isset($array['company_id']))... etc.

If you think you need to use an array because you have too many arguments, that's probably a sign that the function is too complicated and needs to be split up.

Edit: Note that this is more a general answer, as I'm not sure how it applies to your setter issue, since logically a setter should only take one argument. In your situation, if your $this->something expects an array, give it an array, rather than arguments that you have to then turn into an array.

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

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.