【问题标题】:Call a function from a static property in PHP从 PHP 中的静态属性调用函数
【发布时间】:2018-04-04 04:37:40
【问题描述】:

我正在尝试从类中的静态属性直接调用函数。

这是我课堂的摘录:

class Uuid {
  const VERSION_3 = 3;
  const VERSION_5 = 5;
  protected static $hash_function = [
    self::VERSION_3 => 'md5',
    self::VERSION_5 => 'sha1',
  ];

  protected static function get_hash_value($value_to_hash, $version) {
    // None of these work:
    //$hash = self::$hash_function[$version]($value_to_hash);
    //$hash = (self::$hash_function[$version])($value_to_hash);
    //$hash = (self::$hash_function)[$version]($value_to_hash);

    // Only this works:
    $function = self::$hash_function[$version];
    $hash = $function($value_to_hash);
    return $hash;
  }
}

到目前为止,我发现使它工作的唯一方法是在调用之前将函数名存储在一个临时变量 ($function) 中。我试过用大括号({})、括号(())、前缀$等将表达式(或表达式的位)括起来,但到目前为止还没有已经奏效了。

有没有一种简单的方法可以在没有临时变量的情况下做到这一点?如果是这样,它适用于的最低 PHP 版本是多少?

【问题讨论】:

  • 我是call_user_func()call_user_func_array() 的忠实粉丝,因为我打了这种电话。是的,正如您发现的那样,您需要带有函数名称的临时变量来调用它。
  • call_user_func( static::$hash_function[$version], $value_to_hash ); 是我认为的一种选择?

标签: php function static class-properties


【解决方案1】:

是的,正如您所发现的,您需要将函数名称作为一个完整的字符串存储为一个简单的变量,以便能够调用它。此功能的文档可以在 http://php.net/manual/en/functions.variable-functions.php

找到

http://php.net/manual/en/function.call-user-func.php 是另一种选择。

call_user_func( static::$hash_function[$version], $value_to_hash );

另请参阅is_callable()call_user_func()variable variablesfunction_exists()

【讨论】:

    猜你喜欢
    • 2018-04-18
    • 2021-03-07
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    相关资源
    最近更新 更多