1

I'm not so advanced with PHP and am looking for the best solution to the following:

  • I have a PHP array that holds important information about my script that

I need to RE-USE this frequently in my script.

$my_settings = array('width'=>'300', 'height'=>'200', ...);
  • I store that in a MySQL db.

  • The PHP script needs to get that array from MySQL once each time it runs in order to know how to compose the view.

(The array will eventually become quite large... Maybe few hundred rows...)

What is the best practice to get and define this array only ONCE in the beginning of my script, so I can re-use it all the time by other functions etc...?

Is it by defining it globally?

global $my_settings;
$my_settings = get_my_settings_from_db();

function returnSetting($key='') {
 global $my_settings;
 return $my_settings[$key];

}

Or is this bad idea?

What is the most efficient way to do it?

Thanks!

6
  • 1
    Never ever use the global keyword. If you are going to need it often I would look into caching. Commented Jul 31, 2012 at 15:14
  • that's pretty much how it's done ... except you don't need the first global $my_settings;. you only need that within functions that will use it. Commented Jul 31, 2012 at 15:14
  • 1
    You also don't need the second global or any global for that matter. Commented Jul 31, 2012 at 15:15
  • 2
    How come you want to do this by using globals instead of passing the array to the function as an argument? I see no huge difference between using function returnSettings($key, $my_settings) and function returnSetting($key='') {global $my_settings;..., you still have to type and by using globals you are adding a variable to global namespace which forces you to remember that you've done it, and hope you didn't overwrite something already living in the global namespace. Basically, it's a bad idea. Commented Jul 31, 2012 at 15:15
  • @Jamie - this reminds me of killing a mosquito with a rifle. Why use the rifle for such a trivial task - it's beyond me :) Commented Jul 31, 2012 at 15:22

5 Answers 5

4

Instead of using global (which is a bad thing to do) you should inject the variable (or even better the part you need into the function that needs it):

$my_settings = get_my_settings_from_db();

function returnSetting($settings, $key='') {
     return $settings[$key];
}

returnSetting($my_settings, $key);

Or perhaps better create a settings class:

class Settings
{
    protected $settings;

    public function __construct($settings)
    {
        $this->settings = $settings;
    }

    public function getSetting($key)
    {
        return $this->settings[$key];
    }
}

// you only create one instance per request, so you would do this in for example your bootstrap file
$settings = new Settings($my_settings);

Let's say you have a class which needs some settings you could do the following:

class Foo
{
    protected $settings;

    public function __construct($settings)
    {
        $this->settings = $settings;
    {

    public function bar()
    {
        // do something which requires a setting
        echo $this->settings->getSetting('dimensions');
    }
}

$settings = new Settings($my_settings);
$foo = new Foo($settings);
$foo->bar();

When doing it this you will make you code better testable and maintainable.

Note this is just something I written with a beer in one hand and it is untested, but you should get the idea. :-)

Sign up to request clarification or add additional context in comments.

18 Comments

By dependency injection into the classes / function that need it.
@DanielAranda sigh this class doesn't do the same as global. I told you that your definition basically had the same problems as when using the global keyword. I.e. global state and tight coupling.
I'm not talking about scope! sigh! I'm talking about the added value on both codes, both do the same, the problem is that your class is only accessible where it is declared, in other areas that does not have access to the instance that you created, how they get the value? they will not have access, so you method fail. This is the reason because if we do not want to use static var(the easiest way) we must apply patterns like Singleton, instead of what you are suggesting. :P
@DanielAranda , please ,stop embarrassing yourself.
@neokio Did you even open the link about dependency injection? Or don't take my word.
|
0

You don't need the first global like this:

$my_settings = get_my_settings_from_db();

function returnSetting($key='') {
 global $my_settings;
 return $my_settings[$key];

}

Comments

0

Global is nice! <- it is what I will say if Today was July, 2002

But in the 2012 global must be killed by all of the Ninja devs.

Try to use a static var for this:

class DataCollector{
    static $my_settings = array('width'=>'300', 'height'=>'200');
}

//You could use the values at ANY place or function
echo DataCollector::$my_settings['width'];

Also read about OOP basics.

14 Comments

static is the same as a global in this example.
static variables are not part of object oriented paradigm
@DanielAranda: Apart from the $-sign in front of the label, how can one not see that $global and global_class_name::$global is actually the same type of variable? Look what you write. And look what you need to know to access that variable: it's global label. And how do both actually differ apart from the slight difference in syntax? Not at all. Both are globally accessible variables in PHP.
@hakre the question is "PHP How to access this array GLOBALLY?" I answered that, with a better syntax for this times. Also regarding of best practices to build a Settings class we could create another topic, that is my point.
The less intrusive and more clear a syntax is, the better. From that standpoint, just using a global variable is OK. However the way you coin your answer makes no sense. First you tell global variable's aren't the mode of current times (which is not a reason at all), and then only to tell that a slightly differently looking global variable "chest la mode". So you obviously are not giving any arguments but you're discussing styling questions for no obvious reasons. That can never be a better syntax. And this has nothing to do with patterns or paradigms. But who to convince?
|
-1

use $GLOBALS['my_settings']

$GLOBAL is a php super global variable which can be used instead of 'global' keyword to access variables from global scope, i.e. the variables which can be accessed from anywhere in a php script even within functions or methods.

$my_settings = array('width'=>'300', 'height'=>'200', ...);
function blablabla() {
  $b = $GLOBALS['my_settings'] ;
  echo $b ;
}

1 Comment

$GLOBAL is a php super global variable which can be used instead of 'global' keyword to access variables from global scope, i.e. the variables which can be accessed from anywhere in a php script even within functions or methods.
-2
function getSettings($id, $type) {
if(!$id == 0) {
$sql = "SELECT * FROM 'database' WHERE 'id' = '".$id."'";
$result = mysql_query($sql);

if(mysql_num_rows($result) == 0) {
while($row = mysql_fetch_assoc($result)) {
if($type == "setting1") {
        return $row['setting1'];
    } elseif($type == "setting2") {
        return $row['setting2'];
    } elseif($type == "setting3") {
        return $row['setting3'];
    } elseif($type == "setting4") {
        return $row['setting4'];
    } else {
        return "Wrong Input";
        }
} } else { return "Not Initialized";}
else { return "No $id input"; }}}

Store login in $_SESSION and call with getSetting($_SESSION['id'], "setting1")

2 Comments

this option gives me the runs
Please don't use mysql_* functions in new code. They were removed from PHP 7.0.0 in 2015. Instead, use prepared statements via PDO or MySQLi. See Why shouldn't I use mysql_* functions in PHP? for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.