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

时间:2015-09-15 14:15:05

标签: php function parameters conventions readability

关于代码可读性:

我一直在处理这个问题很长时间以来我总是想知道处理传递参数的最佳方法是什么。

很多次,从其他程序员那里读代码我发现这样的行:

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

这使得我必须转到Class文件并查看这些参数的含义。

我会尽力编写可读代码:

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

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

或者这个:

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

但是这些变量占用了内存,而不是在其他地方使用。 我喜欢认为这个“丢失”的记忆空间值得更具可读性,但我想知道是否有更好的方法。

有什么想法吗?

全部谢谢!

2 个答案:

答案 0 :(得分:1)

这样的事情:

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

将数组传递给函数。这样,您就可以看到各个变量的可读性,并且可以根据需要轻松地向函数添加更多/更少的内容。

答案 1 :(得分:0)

首先,在极端情况下,函数可以有很多参数,但通常如果你有很多参数 - 重构。在给定的情况下,看起来应该有一些User对象必须仅传递给函数,并且您可以从函数内的该对象获取所有必需的数据。并且还使用PHPDoc,因为@m_pro_m表示你的IDE会告诉你你需要什么。

也是这种做法

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

因为所谓的“magic numbers and strings”而不好。如果你找到这样的东西,把它们导出到一个常量或一些配置。