如何找出以前叫过哪个班级?

时间:2012-06-19 15:10:57

标签: php late-static-binding

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

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();

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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_called_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
    });
  }
}