0

I'm trying to directly call a function from a static property inside a class.

Here is an extract of my class:

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;
  }
}

The only way I've found of making it work so far is to store the function name in a temporary variable ($function) before calling it. I've tried wrapping the expression (or bits of the expression) in braces, ({,}), parentheses ((,)), prefixing a $, etc. but so far nothing has worked.

Is there a simple way of doing this without a temporary variable? If so, what is the minimum version of PHP this works for?

CJ Dennis
  • 4,226
  • 2
  • 40
  • 69
  • I'm a big fan of `call_user_func()` and `call_user_func_array()` for making this kind of call. And yes as you've found you need that temporary variable with the function name to invoke it as such. – Scuzzy Apr 04 '18 at 04:39
  • `call_user_func( static::$hash_function[$version], $value_to_hash );` would be one option I _think_ ? – Scuzzy Apr 04 '18 at 04:42

1 Answers1

0

Yes, as you've discovered you need to store the function name as a complete string as a simple variable to be able to invoke it. The documentation for this functionality can be found at http://php.net/manual/en/functions.variable-functions.php

http://php.net/manual/en/function.call-user-func.php is another alternative.

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

See also is_callable(), call_user_func(), variable variables and function_exists().

Scuzzy
  • 12,186
  • 1
  • 46
  • 46