简体   繁体   中英

PHP MVC Globals Variables

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..

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM