dongyun3897
dongyun3897
2015-01-31 14:58

为什么[]表示法用于将元素输入到静态数组[复制]

已采纳

This question already has an answer here:

in the original example $methods is a static array.It is used to assign outsider functions as methods to a class.But to input new element to this array writer used the following expression

static protected $methods = array();

i removed the static keyword from the variable declaration and tried to execute the code.

protected  $methods = array();

the execution gave the following error:

Fatal error: Access to undeclared static property: Dynamic::$methods in C:\xampp\htdocs\practice\json.php on line 6

what is this [ ] notation is used for and how it is related to static keyword??

original full code:

class Dynamic {
  static protected $methods = array();

  public static function registerMethod($method) {
    self::$methods[] = $method;
  }

  private function __call($method, $args) {
    if (in_array($method, self::$methods)) {
      return call_user_func_array($method, $args);
    }
  }
}

function test() {
  print "Hello World" . PHP_EOL;
}

Dynamic::registerMethod('test');
$d = new Dynamic();
$d->test();
</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dsshsta97935 dsshsta97935 6年前

    what is this [ ] notation is used for and how it is related to static keyword??

    The use of static and [] are unrelated.

    The code $array[] = $i is a shorthand for pushing the element $i onto the end of the array $array. It could also be written array_push($array, $i).

    点赞 评论 复制链接分享

相关推荐