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

如何在函数中引用全局实例化的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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码