PHP特征 – 更改继承类中静态属性的值

前端之家收集整理的这篇文章主要介绍了PHP特征 – 更改继承类中静态属性的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以,这是我的特点:
  1. trait Cacheable
  2. {
  3. protected static $isCacheEnabled = false;
  4. protected static $cacheExpirationTime = null;
  5.  
  6. public static function isCacheEnabled()
  7. {
  8. return static::$isCacheEnabled && Cache::isEnabled();
  9. }
  10.  
  11. public static function getCacheExpirationTime()
  12. {
  13. return static::$cacheExpirationTime;
  14. }
  15. }

这是基类:

  1. abstract class BaseClass extends SomeOtherBaseClass
  2. {
  3. use Cacheable;
  4. ...
  5. }

这是我的2个最后课程:

  1. class Class1 extends BaseClass
  2. {
  3. ...
  4. }
  5.  
  6. class Class2 extends BaseClass
  7. {
  8. protected static $isCacheEnabled = true;
  9. protected static $cacheExpirationTime = 3600;
  10. ...
  11. }

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

  1. function baseClassRunner($baseClassName)
  2. {
  3. ...
  4. $output = null;
  5. if ($baseClassName::isCacheEnabled()) {
  6. $output = Cache::getInstance()->get('the_key');
  7. }
  8. if ($output === null) {
  9. $baseClass = new $baseClassName();
  10. $output = $baseClass->getOutput();
  11. if ($baseClassName::isCacheEnabled()) {
  12. Cache::getInstance()->set('the_key',$output);
  13. }
  14. }
  15. ...
  16. }

代码不起作用,因为PHP抱怨在Class2中定义与Cacheable中相同的属性.我无法在它们的构造函数中设置它们,因为我想在运行构造函数之前读取它们.我是开放的想法,任何帮助将不胜感激.

猜你在找的PHP相关文章