37

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

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

在 PHP 中

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

5 回答 5

47

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

单例模式

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

class Singleton
{
    private static $instance = null;

    private function __construct()
    {
    }

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

        return self::$instance;
    }
}

工厂方法

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

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);
    }
}

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

于 2012-09-23T14:46:53.717 回答
36

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

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

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

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

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

于 2012-09-23T14:38:11.170 回答
4

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

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

于 2012-09-23T14:33:04.743 回答
3

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

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

    $token = 令牌::generate();

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

于 2012-09-23T14:35:29.333 回答
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;
}
于 2012-09-23T14:35:20.027 回答