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条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c