views:

69

answers:

3

Hi,

I want to use some kind of data structure in PHP (5.2), mainly in order to not pollute the global namespace. I think about two approaches, using an array or a class. Could you tell me which approach is better ?

Also, the main purpose would be for storing configurations constants.

Thanks

$SQL_PARAMETERS = array (
    'server' => '127.0.0.1',
    'login'  => 'root');

class SqlParameters {
    const SERVER = '127.0.0.1';
    const LOGIN  = 'root';
}

echo $SQL_PARAMETERS['server'];
echo SqlParameters::SERVER;
+4  A: 

I'd say that class approach is better because you won't overwrite const or the whole class by accident. And you can also extend your class with some methods should you need them later on.

RaYell
@RaYell: I agree @Double Gras: remember that an object can have objects as attributes as well, thus making complex data structures a piece of cake =) OOP FTW
dabito
+2  A: 

Unless you're going to want to create methods and multiple instances, an array will be just fine.

Eric
A: 

You said you want to avoid polluting your global namespace yet creating an array will do just that: create a global variable that you will be forced to call inside of your classes. This is not best practice and you should strive to avoid global variables at all costs. The class example you posted in your question would be the acceptable solution, also for the reasons that RaYell pointed out.

Jarrod
I choosed this answer, but RaYell's answer is interesting too
Double Gras