可能重复:
在 PHP5 类中,什么时候调用私有构造函数?
我最近一直在阅读有关 OOP 的内容,并遇到了这个私有构造函数场景。我进行了 Google 搜索,但找不到任何与 PHP 相关的内容。
在 PHP 中
在多种情况下,您可能希望将构造函数设为私有。常见的原因是,在某些情况下,您不希望外部代码直接调用构造函数,而是强制它使用另一种方法来获取类的实例。
您只希望存在一个类实例:
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/math的BigDecimal
实现的简化示例什么时候我们必须定义私有构造函数?
class smt
{
private static $instance;
private function __construct() {
}
public static function get_instance() {
{
if (! self::$instance)
self::$instance = new smt();
return self::$instance;
}
}
}
使用私有构造函数的目的是什么?
它确保类只能有一个实例,并为该实例提供一个全局访问点,这在单例模式中很常见。
使用私有构造函数有哪些优点和缺点?
私有构造函数在两种情况下使用
getInstance()
函数使用工厂函数生成对象时 在这种情况下,将会有多个对象,但该对象将由静态函数创建,例如
$token = Token::generate();
这将生成一个新的Token对象。
私有构造函数在大多数情况下用于实现单例模式,或者如果您想强制使用工厂。 当您想要确保只有一个对象实例时,此模式非常有用。 它是这样实现的:
class SingletonClass{
private static $instance=null;
private function __construct(){}
public static function getInstance(){
if(self::$instance === null){
self::$instance = new self;
}
return self::$instance;
}