我需要一种实用的方法将多个参数传递给一个函数,该函数在几个脚本上全局使用,以从数据库转储表。
它接受多个参数(每个参数都有默认值),这取决于脚本是否需要在函数内激活特定选项。
例如:
function dump_table($sumtotal=false, $countrows=false, $yadalada=false... etc){
问题是,如果我有10个不同的参数且脚本只需要参数10为真,我必须调用这样的东西:
dump_table(false,false,false,false...., true)
那么......有没有其他方法可以在没有函数调用开销的情况下轻松扩展它?
我虽然使用对象,但afaik它会涉及每次调用时的类和实例创建。
有没有办法在php(javascript-like style)中制作类似的东西:
dump_table({opt1: true, opt10: true, opt99: true})
甚至
$options = { count: true, sumtotals: true };
dump_table($options);
property_exists
的内容来检查要设置的内容...... THX
答案 0 :(得分:0)
正如@CBroe建议的那样,关联数组可能是您正在寻找的解决方案:
$options = array(
'count' => true,
'sumtotals' => true,
'option3' => false,
...
'option9' => false
);
dump_table($options);
答案 1 :(得分:0)
我会将一些默认选项数组和一个数组作为输入来覆盖:
session Ids
答案 2 :(得分:0)
您可以使用这种方法:
final BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> gattServerConnectedDevices = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT_SERVER);
for (BluetoothDevice device : gattServerConnectedDevices) {
Log.d("Tag", "Found connected device: " + device.getAddress());
}
用法:
function yourFunction(array $parameters = array()) {
//here you should define all possible parameters with their defaults
$param_1 = true;
$param_2 = false;
...
$param_10 = true;
...
$param_N = 'whatever';
//and now simply extract passed parameters
extract($parameters, EXTR_OVERWRITE | EXTR_IF_EXISTS);
}
yourFunction(['param_1' => false, 'param_10' => 'something']);
将使用通过extract($parameters, EXTR_OVERWRITE | EXTR_IF_EXISTS)
数组传递的变量覆盖默认定义的变量。
答案 3 :(得分:0)
这绝对是错误的做法。 我建议使用json_encode()和json_decode()来编码和解码数组。 您可以将所有属性设置为数组。
$array = array(
"sumtotal" = false,
"countrows" =false,
"yadalada" = false
);
dump_table(json_encode($array));
在函数内部,您必须解码该数组json_decode($array, true);
,然后您可以构建您的if else语句