【问题标题】:PHP, set default function parameter to result of functionPHP,将默认函数参数设置为函数结果
【发布时间】: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 您想发布使用回调实现的答案吗?不知道你会怎么做。

标签: php function


【解决方案1】:

docs 里说的对,这个做不到。

所以它必须像下面这样实现......

public static function sha512($token,$cost = 50000,$salt = null) {
    $salt = ($salt == null) ? (self::generateToken(16)) : ($salt);
    $salt = '$6$rounds=' . $cost . '$' . $salt . ' $';
    return crypt($token, $salt);
}

【讨论】:

    【解决方案2】:
    public static function sha512($token,$cost = 50000,$salt) {
        $salt = self::generateToken(16);
        $salt = '$6$rounds=' . $cost . '$' . $salt . ' $';
        return crypt($token, $salt);
    }
    

    【讨论】:

    • 欢迎来到 Stack Overflow!强烈建议您包含一些散文,以帮助其他人理解为什么如何您的解决方案解决了问题。
    【解决方案3】:

    public static function sha512( $token, $cost = 50000, $salt = null )

    更具体地说是$salt = null

    但我希望将默认值作为返回值 另一个函数。

    保持这种意图,这在 PHP 中是不可能的,PHP 不支持一流的函数。正如我在上面的评论中提到的,我看到的唯一解决方法是使用回调。

    据我了解,$salt 参数旨在使用您可能喜欢的盐或默认为代码中的默认盐。

    所以这是一个可能的解决方案,尽管我相信您已经回答了自己的问题:

    public static function sha512( $token, $salt = null, $cost = 50000 ) {
    
        // if a custom salt is provided
        if( isset( $salt ) ) {
    
            // calls the callback function passed in as a param
             $salt = $salt( 16 );
    
            // assemble the result to your specs
            $salt = '$6$rounds=' . $cost . '$' . $salt . ' $';
    
            // return final result
            return crypt( $token, $salt );
        }
    
        // default if no custom salt is provided
        $salt = self::generateToken( 16 );
        $salt = '$6$rounds=' . $cost . '$' . $salt . ' $';
    
        // return final result
        return crypt( $token, $salt );
    }
    

    传入的回调必须在当前作用域内才能成功调用。

    【讨论】:

      猜你喜欢
      • 2011-11-18
      • 2014-04-25
      • 1970-01-01
      • 2011-11-06
      • 2010-10-28
      • 1970-01-01
      • 2012-02-03
      相关资源
      最近更新 更多