开发者

Single array argument versus multiple arguments in PHP

开发者 https://www.devze.com 2023-03-18 18:12 出处:网络
public function setSomething($what){ $this->something = $what; } ... $obj->setSomething(array(\'aaa\', \'bbb\', \'ccc\'));
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', $ke开发者_如何学Cy = 'bbb', $key = 'ccc');


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消