donoworuq450547191 2013-03-26 00:38
浏览 37
已采纳

PHP中保持实例全局或功能范围内的最佳实践

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

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 ?

  • 写回答

1条回答 默认 最新

  • douli4337 2013-03-26 00:46
    关注

    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();
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部