Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP traits - change value of static property in inherited class
    text
    copied!<p>So, this is my trait:</p> <pre><code>trait Cacheable { protected static $isCacheEnabled = false; protected static $cacheExpirationTime = null; public static function isCacheEnabled() { return static::$isCacheEnabled &amp;&amp; Cache::isEnabled(); } public static function getCacheExpirationTime() { return static::$cacheExpirationTime; } } </code></pre> <p>This is the base class:</p> <pre><code>abstract class BaseClass extends SomeOtherBaseClass { use Cacheable; ... } </code></pre> <p>These are my 2 final classes:</p> <pre><code>class Class1 extends BaseClass { ... } class Class2 extends BaseClass { protected static $isCacheEnabled = true; protected static $cacheExpirationTime = 3600; ... } </code></pre> <p>Here is the part of the code which executes these classes:</p> <pre><code>function baseClassRunner($baseClassName) { ... $output = null; if ($baseClassName::isCacheEnabled()) { $output = Cache::getInstance()-&gt;get('the_key'); } if ($output === null) { $baseClass = new $baseClassName(); $output = $baseClass-&gt;getOutput(); if ($baseClassName::isCacheEnabled()) { Cache::getInstance()-&gt;set('the_key', $output); } } ... } </code></pre> <p>This code doesn't work because PHP complains about defining same properties in Class2 as in Cacheable. I can't set them in their constructors because I want to read them even before running the constructor. I'm open for ideas, any help would be appreciated. :)</p> <p>EDIT:</p> <p>Well, I use this Cacheable trait on several places so i kind of got mixed up. :) This works fine like this. But I have another class which directly uses the Cacheable trait and when I try to do this on that class, I get the metioned error. So... Just assume that the BaseClass isn't abstract and I'm trying to set these cache properties on it. The question remains the same.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload