【问题标题】:Parent's class static variable different value for child's classes父类静态变量对于子类的不同值
【发布时间】:2017-01-10 14:02:46
【问题描述】:

请原谅我的英语。

我的问题:

abstract class Entity
{
    protected static $fieldNames;

    public static function getFieldsNames()
    {
        if (is_null(static::$fieldNames)) {
            foreach (static::$fieldsMap as $name => $map) {
                static::$fieldNames[] = $name;
            }
        }

        return static::$fieldNames;
    }
}

class User extends Entity
{
    protected static $fieldsMap = [
        'id' => [
            // ...
        ],
        'name' => [
            // ...
        ],
        'phone' => [
            // ...
        ]
    ];
}

class Car extends Entity
{
    protected static $fieldsMap = [
        'id' => [
            // ...
        ],
        'brand' => [
            // ...
        ],
        'color' => [
            // ...
        ]
    ];
}

print_r(User::getFieldsNames());
// ['id', 'name', 'phone'] - On first call it works as expected, but...

print_r(Car::getFieldsNames());
// ['id', 'name', 'phone'] :(

如果我在 User 和 Car 类中声明 $fieldNames 可以正常工作,但在实际项目中我有数十个静态变量,例如 $fieldNames 和数百个实体

有没有可能最好的解决方案?

也许创建一个小的存储库类,将通过实体的 id 保留这些静态变量?还是其他优雅的方式?

感谢任何帮助!

【问题讨论】:

  • 可能是因为$fieldNames 是静态的;并且您正在检查它是否已经填充if (is_null(static::$fieldNames)) {,因此它不会为不同的子类重新填充...为什么不简单地使用return static::$fieldsMap;
  • 如果你想在继承中使用静态方法/变量,那么请确保你使用的是PHP7,因为旧版本有很多限制。
  • @Mark Ba​​ker 在实际项目中将使用计算/处理值的数十个静态变量,我只想为每个实体设置一次这些值,同时运行时脚本以获得更好的性能,因此,我可以'不要只使用'return static::$var'
  • @Crouching Kitten 是的,php 7.0
  • 那么不要构建一个一次性的静态映射,然后所有类都存在;或构建实例图...但我看不出您的真实项目变量值/数量如何与我的建议产生任何问题;您仍然需要为每个类实体定义单独的 $fieldsMap

标签: php class static


【解决方案1】:

$fieldNames 是静态的,因此它与类本身相关联,而不是与特定对象相关联。 此实例中的类是“实体”。 一旦你设置它就不再为空了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 2017-05-21
    • 2010-12-23
    • 1970-01-01
    • 2013-10-27
    • 2015-04-12
    相关资源
    最近更新 更多