本文介绍了当我们应该使构造函数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;
}
}
}

使用私有构造函数?



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



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






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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 13:43