Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

PHP Constant Arrays?

  1. Dec 21, 2009 #1
    I was wondering if was possible to create a constant array in php so it doesn't have to be reinitialized each time you enter a function. I guess one solution is to make it global but from a code maintenance perspective it makes since to put the array in with the function that uses it.
  2. jcsd
  3. Dec 22, 2009 #2


    User Avatar
    Science Advisor
    Homework Helper

    If I understand your question correctly, you might be looking for a static variable.
    I used it myself in the following two constructions (incidentally, from the same file, so I'll post them both):


        function connect_db() {
            static $theDatabase = null;
            if(!$theDatabase) {
                global $databaseProperties;
                $theDatabase = new db($databaseProperties['dbname'], $databaseProperties['host'], $databaseProperties['user'], $databaseProperties['password'], $databaseProperties['persist']);
            return $theDatabase;

        function getLanguageList() {
            static $languageList = null;
            global $db;
            if($languageList === null) {
                if(!$db) $db = connect_db();
                $languageList = $db->q("column SHOW COLUMNS FROM `TranslatedStrings`");
            return $languageList;
    In both functions, the static variable only exists within the function, but not outside it. The value is kept between calls however. For example, I can call connect_db() as much as I like. The first time, it will create a new database handle, store it in the static variable and give it to me. However, every next time I call the function, it will see that the variable has already been assigned and will just return the value.

    The second example is more similar to your question, that's why I included it. The first time, an array is initialized with some values from a database, a relatively slow operation. After that however, the function basically does nothing but "return $languageList;" where $languageList has the value from the first call.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook