是否可以通过某种方式将函数作为默认参数传递?

时间:2019-07-07 06:03:53

标签: php

我知道我可以将$ at = false保留为默认值,然后在$ at == false时再次设置$ at变量,但是我很想知道是否还有其他捷径。

go_remote_libraries(
  rev='342b2e1fbaa52c93f31447ad2c6abc048c63e475',
  packages=[
    'transform',
    'unicode/norm',
  ]
)

1 个答案:

答案 0 :(得分:1)

否,您不能调用提供默认参数值的函数。 As the docs put it,“ 默认值必须是一个常量表达式,而不是(例如)变量,类成员或函数调用。

我认为编写所需函数的一种惯用方式是使用默认的null值,并使用一个docblock来解释null的含义,即:

/**
 * @param ?string $at reference creation time in Y-m-d H:i:s format, or null for now.
 */
 public function insert_user_to_user_reference(
    string $referrer_id,
    string $referee_id,
    ?string $at = null
 )
 {
     if ($at === null) {
         $at = date('Y-m-d H:i:s');
     }
     //some code here ...
 }
相关问题