简体   繁体   中英

Best practice in PHP to keep instances global or within function scope

I have a class which is used by amfphp and I am using some other classes in it to do multiple tasks. I am curious that what will be the best practice to keep instances of those classes either global or within function scope.

for eg

For global variable $config. I use it like this in functions:

global $config;

For scope variable I do this.

$config = new Config();

now when my program runs it process the specific task and shutdown everything(I assume) and for another different task call same again.

Now which one is better and performance effective ?

As PHP is request based it does not make a big difference where you inizialize an object, as it is recreated on every request anyway, but using globals is considered bad practice and should not be used in new code IMO.

I would recommend creating a config class like in the second example, but if you need it in several places in your code, do not create a new instance every time, but use dependency injection or the singelton pattern.

Singleton:

public class Config
{
    protected static $instance;
    public static Instance()
    {
        if(self::instance === null)
            self::instance = new Config(self::key);
        return self::instance;
    }

    private static $key = "213453452";
    public function __construct($key)
    {
        if($key !== self::key)
            throw new InvalidArgumentException("Private Constructor");
    }

    //your config
}

Dependency Injection (simple example):

public class MyClass
{
    protected $config;

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

    public function DoWork()
    {
        $subClass = new MySubClass($this->config);
        //To Stuff
    }
}

$config = new Config();
$myClass = new MyClass($config);
$myClass->DoWork();

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