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

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.

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.

In elements.php

<?php
return array( // use return so you can retrieve these into a variable
      "sam" => 6, ... and so on ...

Then in the class

<?php
class ArrayAccess {
    public static $elements = null; // set up a static var to avoid load this big array multiple times
    public static function get_value_from_element($element) {
        if(self::$elements === null) { // check if null to load it from the file
            self::$elements = require('elements.php');
        }
        return self::$elements[$element]; // there you go
    }
}

If you don't want do the if statement in the getter every time, you should probably find some where else to load the file into the static variable before using the getter.

An alternative is to declare $elements as global in your class:

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

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