【发布时间】:2021-09-25 14:21:30
【问题描述】:
我有几个具有这种结构的模型:
class Test extends \yii\db\ActiveRecord
{
public static string $defaultDateRange = 'month'; // This property is the same in all classes
public static array $fields = ['name', 'price']; // This property is unique for each class
// This function is the same in all classes
public static function batchUpdate(array $preparedData): int
{
// A class variable is used here - self::$fields
}
// This function is different in all classes
public static function prepareData(array $data): array
{
// ...
}
}
模型既有共同的属性和功能,也有自己独特的。我想优化代码以删除重复的代码段,但我不知道该怎么做。
我尝试创建一个基类并在其中定义所有重复的属性和方法。但是我无法以任何方式获取子元素 Test::$fields 的属性值。
class BaseMarketplaceMetric extends \yii\db\ActiveRecord
{
public static string $defaultDateRange = 'month';
public static function batchUpdate(array $preparedData): int
{
// Need access to a property of a child class - Test::$fields
}
}
class Test extends BaseMarketplaceMetric
{
public static array $fields = ['name', 'price'];
public static function prepareData(array $data): array
{
// ...
}
}
如何获取父类中子类的静态属性值?或者这一切都需要以完全不同的方式完成?
【问题讨论】:
-
我刚刚在 REPL 中测试了它,我从
Test::$fields中得到了数组。你得到了什么? -
标题中的问题与正文中的问题不同。你能让它们更清楚吗?
-
@Geoffrey 如果这样写
Test::$fields,那么我会得到值。但事实是像 Test 这样的几个类,我无法绑定到特定的 Test 类。 -
@daniilsidorov,请添加您尝试如何操作的代码。