Created
March 31, 2009 04:06
-
-
Save speedmax/88047 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Backward compat version of get_called_class | |
*/ | |
if (!function_exists('get_called_class')): | |
function get_called_class() { | |
$bt = debug_backtrace(); | |
$lines = file($bt[1]['file']); | |
preg_match('/([a-zA-Z0-9\_]+)::'.$bt[1]['function'].'/', $lines[$bt[1]['line']-1], $matches); | |
return $matches[1]; | |
} | |
endif; | |
class AR { | |
static function find() { | |
# Delegate non static call to instance method | |
if (!is_static_call()) { | |
$args = func_get_args(); | |
$self = cached_instance(__CLASS__); # <--- from here __class__ is broken | |
return call_user_func_array(array($self, '__find'), $args); | |
} | |
echo __METHOD__ ."\n<br/>"; | |
} | |
function __construct() { | |
cache_instance(get_class($this), $this); | |
} | |
function __find() { | |
echo __METHOD__ ."\n<br/>"; | |
} | |
} | |
class Person extends AR {} | |
$p = new Person; | |
$p->find(); # trying to access instance $p | |
Person::find(); | |
function is_static_call() { | |
$bt = current(array_slice(debug_backtrace(), 1 ,1)); | |
$f = file($bt['file']); | |
return strpos($f[$bt['line']-1], '->'.$bt['function']) === false; | |
} | |
function cached_instance($class) { | |
if (isset($GLOBALS['__cached_instance'][$class])) | |
return $GLOBALS['__cached_instance'][$class]; | |
} | |
function cache_instance($class, $obj) { | |
return $GLOBALS['__cached_instance'][$class] = $obj; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment