1

我有一个包含许多子类的基类,以及一个用于缓存函数结果的通用函数。在缓存函数中,我如何确定调用了哪个子类?

class Base {
  public static function getAll() {
    return CacheService::cached(function() {
      // get objects from the database
    });
  }
}

class X extends Base {}
class Y extends Base {}
class Z extends Base {}

class CacheService {
  function cached($callback) {
    list(, $caller) = debug_backtrace();

    // $caller['class'] is always Base!
    // cannot use get_called_class as it returns CacheService!

    // see if function is in cache, otherwise do callback and store results
  }
}

X::getAll();
Z::getAll();
4

2 回答 2

1

如果您使用的是 PHP >= 5.3,则可以使用get_called_class().

编辑:为了更清楚,get_called_class()必须在您的Base::getAll()方法中使用。当然,您随后必须告诉CacheService::cached()报告的是哪个类(添加方法参数将是最直接的方式):

class Base {
  public static function getAll() {
    return CacheService::cached(get_called_class(), function() {
      // get objects from the database
    });
  }
}

class X extends Base {}
class Y extends Base {}
class Z extends Base {}

class CacheService {
  function cached($caller, $callback) {
    // $caller is now the child class of Base that was called

    // see if function is in cache, otherwise do callback and store results
  }
}

X::getAll();
Z::getAll();
于 2012-06-19T15:36:00.390 回答
0

尝试使用魔法常数__CLASS__

编辑:像这样:

class CacheService {
  function cached($class, $callback) {
    // see if function is in cache, otherwise do callback and store results
  }
}


class Base {
  public static function getAll() {
    return CacheService::cached(__CLASS__, function() {
      // get objects from the database
    });
  }
}

进一步编辑:使用 get_call_class:

class CacheService {
  function cached($class, $callback) {
    // see if function is in cache, otherwise do callback and store results
  }
}


class Base {
  public static function getAll() {
    return CacheService::cached(get_called_class(), function() {
      // get objects from the database
    });
  }
}
于 2012-06-19T15:14:58.380 回答