【问题标题】:How to get the value of the static properties of a child class in the parent class?如何获取父类中子类的静态属性值?
【发布时间】: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,请添加您尝试如何操作的代码。

标签: php oop


【解决方案1】:

解决方案:

我只是在父类中使用static::$fields 来获取子类的静态属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    相关资源
    最近更新 更多