什么情况下我们应该将类构造函数设为私有[重复]

问题描述 投票:0回答:5

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

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

在 PHP 中

  • 我们什么时候必须定义私有构造函数?
  • 使用私有构造函数的目的是什么?
  • 使用私有构造函数有哪些优点和缺点?
php oop constructor
5个回答
51
投票

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

单例模式

您只希望存在一个类实例:

class Singleton
{
    private static ?Singleton $instance = null;

    private function __construct()
    {
    }

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

        return self::$instance;
    }
}

工厂方法

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

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

    private function __construct(string $value, int $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(): Decimal
    {
        return new Decimal('0');
    }

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

        // ...

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

来自brick/mathBigDecimal

实现的简化示例

36
投票

什么时候我们必须定义私有构造函数?

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

使用私有构造函数的目的是什么?

它确保类只能有一个实例,并为该实例提供一个全局访问点,这在单例模式中很常见。

使用私有构造函数有哪些优点和缺点?


4
投票

私有构造函数主要用于单例模式,在这种模式中,您不希望直接实例化您的类,但希望通过其

getInstance()
方法访问它。

这样你就可以确定没有人可以在课堂之外打电话给

__construct()


3
投票

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

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

    $token = Token::generate();

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


1
投票

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

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

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

        }
        return self::$instance;
}
© www.soinside.com 2019 - 2024. All rights reserved.