【发布时间】: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