Bojangles
Bojangles

Reputation: 101473

Performance of storing global constants in a class

I've recently started using classes in my projects, and one of the uses is to set and store global constants in a private array. I'm wondering if this is common practice, bad and, most importantly, slow if I'm doing lots of calls to the fetch function in the class (lots as in, whenever I need the site name, an email address or MySQL details).

I'm not posting the code because it's really basic; just a function that returns the value of an item in the array with the key given.

Upvotes: 2

Views: 212

Answers (2)

user680786
user680786

Reputation:

Don't worry about that.
Going this way, you will come to patterns Singleton and Registry. Don't use these patterns, it's anti-patterns.

Try to build design by the SOLID principles, and your objects will be coupled less and less. The Site Name will be stored in the class, which will output content to the page, and other classes will not need this constant. The Email Address will be stored only in the Mailer class (or in his configuration file), and other classes will not need this constant. And so on.

Class, which contain all constants and all configurations it's kind of a 'God object', and it's an anti-pattern (bad practice) too.

Don't worry about performance of getters and setters.

Upvotes: 2

user743234
user743234

Reputation:

It should be fine unless you declare hundreds of elements in that array, which will look note very nice to get and set :)

What I notice here is that, instead of storing all the information in a private array, why don't you just declare the instance variables? For example, instead of

<?php
class Test() {
    private info = array('sitename' => 'Site Name'; 'database' => 'Database Name');
}
?>

It should be a better practice to do like this

<?php
class Test() {
    private sitename = 'Site Name';
    private database = 'Database Name';
}

?>

The reason behind this is that, when you need to get a single piece of information of your website, you don't need to get the whole array and just get a element of it, which look not very nice. Using instance variables is just more convenient to get and set.

<?php
$test = new Test();
echo $test->info['sitename'];
$test->info['database'] = 'testDB';
?>

Does it look nicer and more handy with this code below?

<?php
$test = new Test();
echo $test->sitename;
$test->database = 'testDB';
?>

Upvotes: 0

Related Questions