dongyong6428 2013-03-07 18:28
浏览 10
已采纳

PHP - 常量数组

I have a small PHP script where it makes sense to use globals. One of the globals is an array that simply contains values to be unpacked but not modified by several different functions. If the script ever expands, the idea of having a global array is a bit unsettling. Is there any way to turn a global array into a constant, unmodifiable value? And if so, will I still be allowed to use the implode() function on it?

  • 写回答

4条回答 默认 最新

  • dongtao4319 2013-03-07 18:39
    关注

    PHP constants do not support advanced data structures, so it is not possible to store an array as the value of a constant. Unless you were to do as you mentioned, by exploding the string.

    There are several global variables (called superglobals) which are available from all PHP scope:

    • $_GET
    • $_POST
    • $_REQUEST
    • $_SERVER
    • $GLOBALS

    I'd highly suggest making use of $GLOBALS, and place your array within that array. It'll immediately be available in any function, class, or included file.

    <?php
    $GLOBALS['my_arr'] = array('key1' => 'val1', 'key2' => 'val2');
    
    function my_func() {
      return $GLOBALS['my_arr']['key1'];
    }
    
    print my_func(); // prints: val1
    

    While you could serialize a constant's value or explode it whenever you wanted to grab a value from it, keep in mind transformation operations do take time. Serializing an array, un-serializing a string, or exploding a string are all very unnecessary operations when you can simply append a value to $GLOBALS. If you need to reference a single value from three different scopes in your script, you're forced to un-serialize or explode three separate times. This takes up more memory and most importantly, processing time.

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

报告相同问题?

悬赏问题

  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题