所以,这是我的特点:
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;
...
}
这些是我的最后两节课:
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 特性,所以我有点搞混了。:) 像这样工作得很好。但是我有另一个类直接使用 Cacheable 特征,当我尝试在该类上执行此操作时,我得到了提到的错误。所以......假设 BaseClass 不是抽象的,我正在尝试在其上设置这些缓存属性。问题还是一样的。