get_called_class.inc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /**
  3. * @file
  4. *
  5. * Add support for get_called_class() to < PHP 5.3.
  6. *
  7. * @see http://www.php.net/manual/en/function.get-called-class.php#93799
  8. */
  9. /********************************
  10. * Retro-support of get_called_class()
  11. * Tested and works in PHP 5.2.4
  12. * http://www.sol1.com.au/
  13. ********************************/
  14. if(!function_exists('get_called_class')) {
  15. function get_called_class($bt = false,$l = 1) {
  16. if (!$bt) $bt = debug_backtrace();
  17. if (!isset($bt[$l])) throw new Exception("Cannot find called class -> stack level too deep.");
  18. if (!isset($bt[$l]['type'])) {
  19. throw new Exception ('type not set');
  20. }
  21. else switch ($bt[$l]['type']) {
  22. case '::':
  23. $lines = file($bt[$l]['file']);
  24. $i = 0;
  25. $callerLine = '';
  26. do {
  27. $i++;
  28. $callerLine = $lines[$bt[$l]['line']-$i] . $callerLine;
  29. } while (stripos($callerLine,$bt[$l]['function']) === false);
  30. preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l]['function'].'/',
  31. $callerLine,
  32. $matches);
  33. if (!isset($matches[1])) {
  34. // must be an edge case.
  35. throw new Exception ("Could not find caller class: originating method call is obscured.");
  36. }
  37. switch ($matches[1]) {
  38. case 'self':
  39. case 'parent':
  40. return get_called_class($bt,$l+1);
  41. default:
  42. return $matches[1];
  43. }
  44. // won't get here.
  45. case '->': switch ($bt[$l]['function']) {
  46. case '__get':
  47. // edge case -> get class of calling object
  48. if (!is_object($bt[$l]['object'])) throw new Exception ("Edge case fail. __get called on non object.");
  49. return get_class($bt[$l]['object']);
  50. default: return $bt[$l]['class'];
  51. }
  52. default: throw new Exception ("Unknown backtrace method type");
  53. }
  54. }
  55. }