当有很多要发送的值时,将值传递给函数的最佳方法是什么?

问题描述:

当您必须将许多值传递给函数并且其中一些值是可选的时,定义方法签名的最佳方法是什么.将来,可能我必须传递更多的变量或减去一些传递给函数的值.

What is the best way to define a method signature when you have to pass many values to a function and some of these may be optional. And in future, May be I have to pass more variables or subtract some passed values given to function.

例如:(电话和地址是可选的)

For example: (phone and address are optional)

function addInfo( $name, $dob, $phone='', $address='' ) {
       // Store data
}

addInfo( 'username', '01-01-2000', '1111111' ); // address is not given

OR

function addInfo( $info ) {
    // Store data
}

$info = array( 'name'=>'username', 
               'dob'=>'01-01-2000', 
               'phone'=>'1111111', 
               'address'=>'' );
addInfo( $info );

还有另一种类似于OOP的方法:使用字段名称","dob",电话",地址"创建参数对象(例如person) '(在Fowler的重构"书中称为引入参数对象重构"). 在您的情况下似乎很合适,因为传递给函数的所有字段实际上都与一个对象相关.

There's one more OOP-like way: create parameter object (for example, person) with fields 'name', 'dob', 'phone', 'address' (this is called Introduce Parameter Object refactoring in Fowler's "Refactoring" book). It seems appropriate in your case, since all fields you pass to function actually are related to one object.