gpt4 book ai didi

PHP7.3 : How can I inherit a protected static property with the thightest possible scope without redeclaring it in the child class?

转载 作者:行者123 更新时间:2023-12-01 13:10:52 25 4
gpt4 key购买 nike

在我正在处理的应用程序中,MVC 堆栈的模型部分被设计为通过单例工作;每个模型都有一个 __getInstanceMethod 是

protected static $singleton;
public static function __getInstance(): self {
if(self::$singleton === null) {
self::$singleton = __CLASS__;
self::$singleton = new self::$singleton;
}
return self::$singleton;
}

最终结果是,如果 __getInstance() 在同一个模型类上被调用两次,它两次都会返回完全相同的对象。

我试图通过将 __getInstance() 方法移动到模型的父类 BaseModel 来减少代码重复,方法是像这样编辑它。

class BaseModel {
protected static $singleton;
public static function __getInstance(): self {
if (static::$singleton === null) {
static::$singleton = static::class;
static::$singleton = new static::$singleton();
}
return static::$singleton;
}
}
class AModel extends BaseModel {
protected static $singleton;
/** ... */
}
class BModel extends BaseModel {
protected static $singleton;
/** ... */
}

AModel::__getInstance(); // AModel
BModel::__getInstance(); // BModel

问题是,我需要为每个模型类手动添加一个 $singleton 属性,否则我将始终返回调用该方法的第一个模型类的实例。

class BaseModel {
protected static $singleton;
public static function __getInstance(): self {
if (static::$singleton === null) {
static::$singleton = static::$class;
static::$singleton = new static::$singleton();
}
return static::$singleton;
}
}
class AModel extends BaseModel {}
class BModel extends BaseModel {}

AModel::__getInstance(); // AModel
BModel::__getInstance(); // Still AModel

有什么办法可以避免这样做吗?

最佳答案

您可以切换到“实例映射”,例如:

<?php
declare(strict_types=1);

error_reporting(-1);
ini_set('display_errors', 'On');

class BaseModel
{
protected static $instances = [];

public static function __getInstance(): self
{
if (!isset(static::$instances[static::class])) {
static::$instances[static::class] = new static();
}

return static::$instances[static::class];
}
}

class AModel extends BaseModel
{
}

class BModel extends BaseModel
{
}

echo get_class(AModel::__getInstance()), "\n";
echo get_class(BModel::__getInstance());

https://3v4l.org/qG0qJ


在 7.4+ 中,它可以简化为:

<?php
declare(strict_types=1);

error_reporting(-1);
ini_set('display_errors', 'On');

class BaseModel
{
private static array $instances = [];

public static function __getInstance(): self
{
return static::$instances[static::class] ??= new static();
}
}

关于PHP7.3 : How can I inherit a protected static property with the thightest possible scope without redeclaring it in the child class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60070830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com