drnycqxwz63508434 2015-09-15 14:15
浏览 81

将参数传递给函数的最佳方法?

It's about code readability:

I've been dealing with this for a long time and I always wonder what would be the best approach to deal with passing parameters.

Lots of times, reading code from other programmers I find lines as such:

$Instance->functionCall('Abc123', 5, 1.24, 'XYZ', 642);

This makes me have to go to the Class file and take a look at what those parameters mean.

I do my best to write readable code by doing this:

$user_name = 'Abc123';
$age = 5;
$height = 1.24;
$hobbies = 'XYZ';
$num_brothers = 642;

$Instance->functionCall($user_name, $age, $height, $hobbies, $num_brothers);

Or this:

$Instance->functionCall($user_name = 'Abc123', $age = 5, $height = 1.24, $hobbies = 'XYZ', $num_brothers = 642);

But this variables occupies memory, not being used anywhere else. I like to think that this 'lost' memory space is worth it by being more readable, but I'd like to know if there is a better way.

Any ideas?

Thanks all!

  • 写回答

2条回答 默认 最新

  • douzengjian1535 2015-09-15 14:21
    关注

    What about something like this:

    $Instance->functionCall([         // or $Instance->functionCall( array(
        'user_name'    => 'Abc123',
        'age'          => 5,
        'height'       => 1.24,
        'hobbies'      => 'XYZ',
        'num_brothers' => 642
    ]);
    

    pass an array into the function. That way you have the readability of individual variables and can easily add more/less to the function as needed.

    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数