我们什么时候应该将构造函数设为 Private & 为什么?PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12553142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:47:28  来源:igfitidea点击:

When we should make the constructor Private & Why? PHP

phpoopconstructor

提问by Techie

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

可能的重复:
在 PHP5 类中,何时调用私有构造函数?

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.

我最近一直在阅读有关 OOP 的内容,并遇到了这个私有构造函数场景。我进行了 Google 搜索,但找不到与 PHP 相关的任何内容。

In PHP

在 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?
  • 我们什么时候必须定义私有构造函数?
  • 使用私有构造函数的目的是什么?
  • 使用私有构造函数的优缺点是什么?

回答by Benjamin

There are several scenarios in which you might want to make your constructor private. The common reason is that in some cases, you don't want outside code to call your constructor directly, but force it to use another method to get an instance of your class.

在多种情况下,您可能希望将构造函数设为私有。常见的原因是在某些情况下,您不希望外部代码直接调用您的构造函数,而是强制它使用另一种方法来获取您的类的实例。

Singleton pattern

单例模式

You only ever want a single instance of your class to exist:

您只希望类的单个实例存在:

class Singleton
{
    private static $instance = null;

    private function __construct()
    {
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }
}

Factory method

工厂方法

You want to provide several methods for creating an instance of your class, and/or you want to control the way your instances are created, because some internal knowledge of the constructor is needed to properly call it:

您希望提供多种方法来创建类的实例,和/或希望控制实例的创建方式,因为需要对构造函数有一些内部知识才能正确调用它:

class Decimal
{
    private $value; // constraint: a non-empty string of digits
    private $scale; // constraint: an integer >= 0

    private function __construct($value, $scale = 0)
    {
        // Value and scale are expected to be validated here.
        // Because the constructor is private, it can only be called from within the class,
        // so we can avoid to perform validation at this step, and just trust the caller.

        $this->value = $value;
        $this->scale = $scale;
    }

    public static function zero()
    {
        return new self('0');
    }

    public static function fromString($string)
    {
        // Perform sanity checks on the string, and compute the value & scale

        // ...

        return new self($value, $scale);
    }
}

Simplified example from the BigDecimalimplementation of brick/math

砖块/数学BigDecimal实现的简化示例

回答by Baba

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?

使用私有构造函数的优缺点是什么?

回答by moonwave99

Private constructor is used mostly in Singleton pattern, in which you don't want your class to be instantiated directly, but you want to access it via its getInstance()method.

私有构造函数主要用于单例模式,在这种模式中,您不希望直接实例化您的类,但希望通过其getInstance()方法访问它。

This way you are sure nobody can call __construct()outside of the class itself.

这样你就可以确定没有人可以__construct()在课堂之外打电话。

回答by Joyce Babu

Private constructor is used in two conditions

私有构造函数在两种情况下使用

  1. When using a Singleton Pattern In this case there is only one object and the object will be created usually by a getInstance()function
  2. When using a factory function for generating objects In this case there will be multiple objects, but the object will be created by a static function for example

    $token = Token::generate();

  1. 当使用单例模式时在这种情况下只有一个对象并且该对象通常由一个getInstance()函数创建
  2. 当使用工厂函数生成对象时这种情况下会有多个对象,但对象将由静态函数创建,例如

    $token = Token::generate();

This will generate a new Token object.

这将生成一个新的 Token 对象。

回答by artragis

Private constructors are here to implement the singleton pattern most of time or if you want to force a factory. This pattern is useful when you want to be sure that you have only one instance of the object. it is implemented as this :

私有构造函数在大多数情况下用于实现单例模式,或者如果您想强制使用工厂。当您想确保只有一个对象实例时,此模式很有用。它是这样实现的:

class SingletonClass{
    private static $instance=null;
    private function __construct(){}

    public static function getInstance(){
        if(self::$instance === null){
            self::$instance = new self; 

        }
        return self::$instance;
}