什么时候我们应该让构造函数私有&为什么?PHP

Tec*_*hie 29 php oop constructor

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

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

在PHP中

  • 我们何时必须定义私有构造函数?
  • 使用私有构造函数的目的是什么?
  • 使用私有构造函数的优点和缺点是什么?

Ben*_*min 37

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

单身模式

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

class Singleton
{
    private static $instance = null;

    private function __construct()
    {
    }

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

        return self::$instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

工厂方法

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

来自brick/mathBigDecimal实现的简化示例


Bab*_*aba 33

我们何时必须定义私有构造函数?

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

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

它确保只有一个Class实例并为该实例提供全局访问点,这在Singleton Pattern中很常见.

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