【发布时间】:2015-03-31 00:34:12
【问题描述】:
在 PHP 中,函数可以有可选参数:
public static function test($var = 'default string')
但我想让默认值成为另一个函数的返回值。例如,我有一个名为generateToken() 的方法,它创建了一个所需长度的随机字符串。我尝试执行以下代码...
public static function sha512($token,$cost = 50000,$salt = self::generateToken(16)) {
$salt = '$6$rounds=' . $cost . '$' . $salt . ' $';
return crypt($token, $salt);
}
但是这会引发以下错误...
Parse error: syntax error, unexpected '(', expecting ')' in /var/www/www.domain.com/path/to/cryptography.php on line 11
第11行是方法减速线。我知道这可以通过将默认值设置为'NONE' 之类的东西来完成,然后让 if 语句调用该方法,但我想在方法减速中进行。我该怎么做?
【问题讨论】:
-
在this question上查看答案
-
documentation 很清楚:
The default value must be a constant expression, not (for example) a variable, a class member or a function call. -
我看到的唯一解决方法是使用回调。 php.net/manual/en/language.types.callable.php
-
@samyismyhero 您想发布使用回调实现的答案吗?不知道你会怎么做。