当有很多要发送的值时,将值传递给函数的最佳方法是什么? [英] Best way to pass values to a function when there are many to send?

查看:71
本文介绍了当有很多要发送的值时,将值传递给函数的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于当有很多要发送的值时,将值传递给函数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆