Search code examples
phplate-static-binding

How to find out what class was called previously?


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

Solution

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