使用像$ this :: $ var []这样的变量访问数组

时间:2015-04-15 19:59:19

标签: php

我想根据变量访问静态数组。我的数组看起来像$blacksmith[]$houses[]等。我想避免创建大量的getter,只需使用以下函数执行:

function getNextResPrice($resource, $level){
    return $this::$resource[$level];    
}

然后,如果我想访问$ blacksmith,该函数最终会像:

getNextResPrice("blacksmith", 2)

return $this::$blacksmith[2];

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,您希望以编程方式解析静态类属性并从给定索引中获取值。要做到这一点,你可以尝试这样的事情:

<?php

  class Something {

    static private $houses = [ 1, 2, 3 ];

    static private $blacksmith = [ 9, 8, 7 ];

    static public function getFrom($field, $id) {
      $class_vars = get_class_vars(__CLASS__);

      if (isset($class_vars[$field]) && isset($class_vars[$field][$id])) {
        return $class_vars[$field][$id];
      } else {
        throw new Exception(__CLASS__ . "::${field}[${id}] does not exist");
      }
    }

  }

  print Something::getFrom('houses', 1) . "\n";
  print Something::getFrom('blacksmith', 2) . "\n";

  try {
    print Something::getFrom('dnx', 3) . "\n";
  } catch (Exception $e) {
    print $e->getMessage() . "\n";
  }

  try {
    print Something::getFrom('blacksmith', 123) . "\n";
  } catch (Exception $e) {
    print $e->getMessage() . "\n";
  }

这是预期的输出:

  2
  7
  Something::dnx[3] does not exist
  Something::blacksmith[123] does not exist