当我们应该使构造函数Private&为什么? PHP [英] When we should make the constructor Private & Why? PHP

查看:384
本文介绍了当我们应该使构造函数Private&为什么? PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:






我最近一直在阅读关于OOP,并遇到这个私人构造函数场景。我做了一个Google搜索,但找不到任何与PHP相关的东西。



在PHP




  • 我们什么时候必须定义一个私有构造函数? / li>
  • 使用私有构造函数的目的是什么?

  • 使用私有构造函数的缺点?


解决方案

私人构造函数?

  class smt 
{
private static $ instance;
private function __construct(){
}
public static function get_instance(){
{
if(!self :: $ instance)
self: :$ instance = new smt();
return self :: $ instance;
}
}
}

使用私有构造函数?



它确保只有一个类的一个实例,并为该实例提供一个全局访问点,这是常见的与单身模式。



使用私有构造函数的缺点?




Possible Duplicate:
In a PHP5 class, when does a private constructor get called?

I have been reading about OOP recently and came across this private constructor scenario. I did a Google search, but couldn't find anything relevant to PHP.

In PHP

  • When do we have to define a private constructor?
  • What's the purpose of using a private constructor?
  • What are the pros & cons of using a private constructor?

解决方案

When do we have to define a private constructor?

class smt 
{
    private static $instance;
    private function __construct() {
    }
    public static function get_instance() {
        {
            if (! self::$instance)
                self::$instance = new smt();
            return self::$instance;
        }
    }
}

What's the purpose of using a private constructor?

It ensures that there can be only one instance of a Class and provides a global access point to that instance and this is common with The Singleton Pattern.

What are the pros & cons of using a private constructor?

这篇关于当我们应该使构造函数Private&为什么? PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆