note 94902 deleted from function.get-called-class by danbrown
| From: | danbrown@php.net | Date: | Wed, 02 Dec 2009 15:08:28 +0000 |
| Subject: | note 94902 deleted from function.get-called-class by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-163496@lists.php.net to get a copy of this message | ||
Note Submitter: jurgens dot dutoit at gmail dot com
----
Just a update on laurence+nospam at sol1 dot com dot au's get_called_class function. This adds
support for call_user_func and call_user_func_array:
<?php
/********************************
* Retro-support of get_called_class()
* Tested and works in PHP 5.2.4
* Original http://www.sol1.com.au/
* Update http://backend-php.net/
********************************/
if (!function_exists('get_called_class')) {
function get_called_class($bt = false, $l = 1) {
if (!$bt) $bt = debug_backtrace();
if (!isset($bt[$l])) throw new Exception("Cannot find called class -> stack level too
deep.");
if (!isset($bt[$l]['type'])) {
throw new Exception ('type not set');
} else {
switch ($bt[$l]['type']) {
case '::':
if (array_key_exists('file', $bt[$l])) {
$lines = file($bt[$l]['file']);
$i = 0;
$callerLine = '';
do {
$i++;
$callerLine = $lines[$bt[$l]['line'] - $i] . $callerLine;
} while (stripos($callerLine,$bt[$l]['function']) === false);
preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l]['function'].'/',
$callerLine,
$matches
);
if (!isset($matches[1])) {
// must be an edge case.
throw new Exception ("Could not find caller class: originating method call is
obscured.");
}
switch ($matches[1]) {
case 'self':
case 'parent':
return get_called_class($bt, $l + 1);
break;
default:
return $matches[1];
break;
}
} else if (
array_key_exists('function', $bt[$l + 1])
&& in_array($bt[$l + 1]['function'], array('call_user_func',
'call_user_func_array'))
&& array_key_exists(0, $bt[$l + 1]['args'])
&& is_array($bt[$l + 1]['args'][0])
) {
return current($bt[$l + 1]['args'][0]);
}
// won't get here.
case '->':
switch ($bt[$l]['function']) {
case '__get':
// edge case -> get class of calling object
if (!is_object($bt[$l]['object'])) throw new Exception ("Edge case fail. __get
called on non object.");
return get_class($bt[$l]['object']);
break;
default:
return $bt[$l]['class'];
break;
}
default:
throw new Exception ("Unknown backtrace method type");
break;
}
}
}
}