문제

I have a base class with many sub-classes, and a generic function to cache the results of a function. In the cache function, how do I figure out what sub-class was called?

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();
도움이 되었습니까?

해결책

If you're using PHP >= 5.3, you can do this with get_called_class().

Edit: To make it more clear, get_called_class() has to be used in your Base::getAll() method. You, of course, would then have to tell CacheService::cached() what class this reported (adding a method argument would be the most straight-forward way):

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

다른 팁

Try using the magic constant __CLASS__

EDIT: Like this:

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

FURTHER EDIT: Using 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
    });
  }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top