Why do some php functions 'return' a given parameter?

时间:2016-10-20 13:03:25

标签: php function

I'm not sure if I've phrased this question appropriately but I don't know how else to pose it without giving examples, which I will do.

Examples:

preg_match

preg_match("/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/", $input_line, $output_array);

Why do we give preg_match the parameter of $output_array? It seems not to make sense in the context of how the rest of php works. Wouldn't the following be more conventional?

$output_array = preg_match("/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/", $input_line);

openssl_private_encrypt

openssl_private_encrypt ($data , $encrypted_data , $key);

Again, why do we pass the $encrypted_data to the function? Rather than what 99% of other functions do and return the result which can be used to set a variable's value.

$encrypted_data = openssl_private_encrypt ($data, $key);

Is this a legacy issue? Are there good reasons for doing this with certain functions?

1 个答案:

答案 0 :(得分:2)

由于PHP在优秀的旧核心标准库中抛出异常并不重要,因此它需要一种不同的机制来区分函数操作的两个方面:

  • 操作成功了吗?
  • 返回值是多少?

构建更多异常的语言将具有以下内容:

try:
    value = somefunc()
except SomeError:
    # handle failure

Go等语言返回返回值错误状态指示符:

value, err := somefunc()
if err != nil {
    log.Fatal(err)
}

PHP使用return值作为成功指标,并使用by-reference参数作为返回值,尤其是当返回值不总是感兴趣时:

if (!somefunc($value)) {
    // handle failure
}
echo $value;

否则代码必须看起来像这样:

$value = somefunc();
if ($value === false) {
    // handle failure
} else if ($value === 0) {
    // no match
}
echo $value;

在某些情况下使用返回值,错误指示都不可能返回值,因为false0或两者都可能是合法的返回值而你不能不要将它与错误代码区分开来。如果你不打算使用异常,那么使用by-reference参数来表示“二级”返回值并不是一个糟糕的设计决定。