PHP traits - 更改继承类中静态属性的值

标签 php inheritance properties traits redefinition

所以,这是我的特点:

trait Cacheable
{
    protected static $isCacheEnabled = false;
    protected static $cacheExpirationTime = null;

    public static function isCacheEnabled()
    {
        return static::$isCacheEnabled && Cache::isEnabled();
    }

    public static function getCacheExpirationTime()
    {
        return static::$cacheExpirationTime;
    }
}

这是基类:

abstract class BaseClass extends SomeOtherBaseClass
{
    use Cacheable;
    ...
}

这些是我的 2 门期末课:

class Class1 extends BaseClass
{
    ...
}

class Class2 extends BaseClass
{
    protected static $isCacheEnabled = true;
    protected static $cacheExpirationTime = 3600;
    ...
}

下面是执行这些类的代码部分:

function baseClassRunner($baseClassName)
{
    ...
    $output = null;
    if ($baseClassName::isCacheEnabled()) {
        $output = Cache::getInstance()->get('the_key');
    }
    if ($output === null) {
        $baseClass = new $baseClassName();
        $output = $baseClass->getOutput();
        if ($baseClassName::isCacheEnabled()) {
            Cache::getInstance()->set('the_key', $output);
        }
    }
    ...
}

此代码不起作用,因为 PHP 提示在 Class2 中定义与在 Cacheable 中相同的属性。我不能在它们的构造函数中设置它们,因为我什至想在运行构造函数之前阅读它们。我对想法持开放态度,任何帮助将不胜感激。 :)

编辑:

好吧,我在几个地方使用了这个可缓存的特性,所以我有点混淆了。 :) 这很好用。但是我有另一个直接使用 Cacheable 特性的类,当我尝试在该类上执行此操作时,我得到了提到的错误。所以...假设 BaseClass 不是抽象的,我正在尝试在其上设置这些缓存属性。问题还是一样。

最佳答案

您不能重新分配特征属性。

来自 PHP 手册 http://php.net/traits

参见示例 #12 冲突解决

If a trait defines a property then a class can not define a property with the same name, otherwise an error is issued. It is an E_STRICT if the class definition is compatible (same visibility and initial value) or fatal error otherwise.

一种解决方案是在类中定义覆盖属性

class Class2 extends BaseClass
{
    protected static $_isCacheEnabled = true;
    protected static $_cacheExpirationTime = 3600;
    ...
}

然后修改你的特质......

trait Cacheable
{
    protected static $isCacheEnabled = false;
    protected static $cacheExpirationTime = null;

    public static function isCacheEnabled()
    {

        if ( Cache::isEnabled() ) {
            return isset( static::$_isCacheEnabled ) ? static::$_isCacheEnabled :
                static::$isCacheEnabled;
        } else {
            return false;
        }

    }

    public static function getCacheExpirationTime()
    {
        return isset ( static::$_cacheExpirationTime ) ? static::$_cacheExpirationTime :        
            static::$cacheExpirationTime;
    }
}

关于PHP traits - 更改继承类中静态属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20299369/

相关文章:

php - 为什么 redirect() 不允许我完成函数调用?

php - 压缩字符串,然后解压缩字符串?

php - 学习 ruby​​ 的资源

从 NSObject 继承时,不会调用泛型中使用的 swift 子类

php - 如何从动态添加唯一字段的表单中将数据存储在 mysql 数据库中?

Java创建子类构造函数时出错

html - 覆盖 CSS 移除属性

python - 无法在马尔可夫政权切换模型中的属性类中设置属性

c# - 有没有办法通过反射设置 C# 只读自动实现的属性?

java: 为什么我必须在构造函数的第一行写 super()