Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define hardcoded array data as part of a PHP framework?

Tags:

php

frameworks

For example the 50 united states. Right now I use the 50 states in only a single function:

function getStateInput() {
    $states = array('AL' => 'Alabama', 'AK' => 'Alaska',
        'AZ' => 'Arizona', etc);

    //use $states
}

Alternatively you could define $states in its own states.php and then use it like this:

function getStateInput() {
    include('states.php');

    //use $states
}

But for some reason that scares me because I am using an include to define a local function variable. Another way would be to assign a states array to a superglobal in a states.php (for example I could use $_ENV['states']). Then I could go:

include('states.php');

function getStateInput() {
    //use $_ENV['states']
}

Is one of those best or is there another better way?

like image 824
Ryan Avatar asked Apr 19 '26 00:04

Ryan


1 Answers

The common way is to separate concerns. You can eg. have your own class with address-related methods. This class would be the natural place to store information about possible states, like that:

class Address {
    static STATES = array(
        'AL' => 'Alabama',
        'AK' => 'Alaska',
        'AZ' => 'Arizona',
        // ...
    );
}

// and then you can use it somewhere like that:
echo Address::$STATES['AL'];
like image 146
Tadeck Avatar answered Apr 20 '26 12:04

Tadeck