Proper Way To Include A Separate File.

Hello all,

I’ve made a helper class that deals with times. I have a separate file inside my helper folder called countryCodes.php (pretty similar to the mimeTypes.php that is already there). The only thing it contains is a rather long array of two letter country codes and their respective countries. I’d like to use this array inside a method in my helper class. What is the proper way to include it?

Use the PHP require or require_once method.

Ah thanks for the reply.




    public static function getCountryCodes()

    {

        require_once('countryCodes.php');

        return $countryCodes;

    }



The above code works but is it good practice to put the require statement inside a method? Is there a different technique to do this?

Is there any particular reason why you store this information inside of a php file instead of a database table?

Ideally a database is recommended for such data - but if you need to manage these as PHP arrays - why not create these as directly static variables in your helper class than in a separate file.




class Setup 

{

   public static $countries = [

       'US' => 'United States',

       // etc...

   ];


   public static $provinces = [

       'code1' => 'description1'

       // etc...

   ];

}


public function countryCodes() {

    return array_keys(Setup::$countries);

}



Alternatively if you need to maintain separate files you can do something like this:




$countries = require('countryCodes.php'); // returns an array



and in your countryCodes.php just have this php code




return [

  'US' => 'United States',

  'UK' => 'United Kingdom',

  //etc.

];



Thank you for the answers. The reason I put it in an array is because I copied and pasted it off the internet and it was already formatted as an array. I don’t really see the benefit of migrating it to the database. I put it in a separate file because it is about 200 entries long and while working on my class it just makes the code easier to read. The last answer you posted Kartik V is just what I was looking for. Thanks!

Yes, I kind of understood, where you were getting at. Just ensure your data integrity is correct… as you may not now have referential constraints like foreign key relations, when you are holding such data OUTSIDE YOUR DB.