doujia9204 2012-09-06 16:52
浏览 32
已采纳

PHP对象试图访问外部数组

I have an Object that needs to access a previously declared array in my statistics. I can of course create the entire array inside of the object, but since multiple objects use the exact same array there is no reason to clog up memory or time by making a call to the Database to create the same array every time I create a new object.

So, I understood that Objects cannot access global variables, but is there any work-around to access an external Array from within the object?

example Code:

global $stats = array();
       $stats[1]['value']= 10;
       $stats[1]['value1'] =2;
       $stats[2]['value']= 12;
       $stats[2]['value1'] =1;

class Obj() {

  private $valueA;
  private $valueB;

  function __construct($user) {
    //access Database lets call $SQL;
    $valueA = SQL->value;

  }

  function showA() {
    return ( $valueA * $stats[1]['value1']) + $stats[1]['value'];
  }

}
  • 写回答

4条回答 默认 最新

  • doufengsui7449 2012-09-08 11:03
    关注

    Thanks to Mike, Sheikh and Kristian,

    I can't in all Faith give a tick to your answers, because your words did not help me to understand the answer, Putting 'global $stats;' into the class results in an Error which I pointed out in my responses. but I will 'up' your scores when I permission from the site to do so.

    For anyone looking for the answer to this, a Reminder, the key point is not to store the entire Array in the class, creating a huge waste of memory. The Key point is to gain access to the Variable which exists outside of the class.

    While adding access to the global $stats by including it in the functions of the class, does produce the required results, It still requires that the Data is being stored in the class, which is again, against the point. Sorry I wasn't clear on this from the very beginning.

    Instead:

    example Code:

     function showA(&$stats) {
       return ( $valueA * $stats[1]['value1']) + $stats[1]['value'];
     }
    

    }

    This, if I understand correctly, will use the pointer to the $stats variable, only within the scope of returning the $valueA after it has been modified using the stats array. not copying the entire array into another memory location, nor the class.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度