dtnbjjq51949
2013-11-25 15:07
采纳率: 0%
浏览 91
已采纳

如何在函数中引用全局实例化的PHP对象?

Previously, I had a global array ($v) and referenced it from within functions by using global $v;. I now want to encapsulate everything about that array, so I wrote a class. In the global context, I instantiate the class:

$vi = new my_v();

Within a function I want to call a method of that object:

function f($x) {
  $vi->add($x);
}

How do I refer to $vi within the function?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doumu9799 2013-11-25 15:08
    已采纳

    Use the global keyword:

    function f($x) {
      global $vi;
      $vi->add($x);
    }
    

    You can also use the $GLOBALS superglobal array:

    function f($x) {
      $GLOBALS['vi']->add($x);
    }
    

    See: http://us1.php.net/manual/en/language.variables.scope.php

    Working example: http://3v4l.org/ERIK8

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题