PHP traits - change value of static property in inherited class

泄露秘密 提交于 2019-12-04 05:00:14

You can not reassign trait properties.

From PHP manual http://php.net/traits

See Example #12 Conflict Resolution

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.

One solution would be to define override properties in the class

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

and then modify your trait as such...

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;
    }
}

You cannot override properties, but you can override functions. So one of the possible solutions, if you're going to use the properties as given, not changing them, could be:

trait Cacheable {
    protected static function isCacheEnabledForClass() { return false; }

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


class Class2 extends BaseClass {
    protected static function isCacheEnabledForClass() { return true; }
}

You could use defined():

// only defined in classes
// static $isCacheEnabled = false;

public static function isCacheEnabled()
{
    return defined(static::$isCacheEnabled ) ? static::$isCacheEnabled : false;
}

Or maybe you could live with the variable being protected instead of static?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!