1

I have a little doubt, I understand that using global variables is a bad practice.

I have a small MVC application with php, in which I would like to create a file .. called config.php and inside it, save the global variables that I will use in my classes, example ...

$config = array ();
$config ['db_host'] = 'localhost';

Now, I would like to know what would be the recommended way to include this file in my application .. I have implemented a autoloader, I could include it in this ...

Class Autoload
{
    public function __construct () {
        global $ config;
        require_once 'config.php';
    }
}

But I really do not know if this is a good practice ...

Thank you very much in advance..

2
  • That is not a good practice Commented Jun 6, 2017 at 12:43
  • Hi, thanks for your quick reply. Could you help me find a better way to do it? I really can not think of another one. Many thanks again? Commented Jun 6, 2017 at 12:59

2 Answers 2

2

Generally speaking it's not a good practice to use globals or singletons. What you want instead is called "dependency injection." This pattern enables you to use mock objects for testing. Some of the philosophy and practice of dependency injection is available in this article. https://iconoun.com/blog/2017/05/05/php-globals-vs-dependencies/

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

1 Comment

Wow! .. excellent article, I am reading, when finished reading it, surely you take my best answer .. Many, many thanks for this excellent article
0

Instead of globals you could create a class, like this

class Autoload {

    public $value1;
    public $value2;
    public static instances = array();

    public static function instantiate($className) {
        if (isset($instances[$className])) {
            return $instances[$className];
        }
        $newInstance = new $className();
        $newInstance->value1 = "foo";
        $newInstance->value2 = "bar";
        return $instances[$className] = $newInstance;
    }
}

And you can inherit this class for more specific cases, for instance, different user types.

Comments

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.