doutuo3899 2015-09-16 10:46
浏览 69
已采纳

在静态类中使用另一个文件中的外部数组

I'm currently working on a project where I have to work with huge arrays. With huge, I mean 1k elements or more. Since these are a lot of arrays and i sometimes mess things up, I decided to create a class with static functions so i can call the functions which would make the entire project easier to read. This is what I currently have:

ArrayAccess.class.php:

require "dep/arrays/elements.php";
class ArrayAccess {

    public static function get_value_from_element($element) {
        return $elements[$element];
    }
}

elements.php:

<?php
$elements = array(
    "sam" => 6, ... and so on ...

I simply want to be able to use ArrayAccess::get_value_from_element($element) in my project. It is so much easier to read than all these indexes everywhere. However, the array is defined in the elements.php file - I can't use that in the class.

So how can I access the array in my class? Please note, I cannot copy it into the class, the file would be larger than 400k lines, this is not an option.

  • 写回答

3条回答 默认 最新

  • dongzhuohan7085 2015-09-16 11:09
    关注

    You can return a value from an include (or require in this case) and store that to a static property the first time the function is called.

    elements.php:

    <?php
    return array("sam" => 6, ...);
    

    DataAccess.php:

    class DataAccess {
    
        private static $elements = array();
    
        public static function get_value_from_element($element) {
            if(self::$elements === array()) {
                self::$elements = require "elements.php";
            }
            return self::$elements[$element];
        }
    }
    

    You should also avoid naming your class ArrayAccess, since it already exists in PHP.

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

报告相同问题?

悬赏问题

  • ¥15 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?
  • ¥66 如何制作支付宝扫码跳转到发红包界面