note 89478 modified in function.get-called-class by danbrown

From: Date: Wed, 22 Apr 2009 12:49:24 +0000
Subject: note 89478 modified in function.get-called-class by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153581@lists.php.net to get a copy of this message
Simplified version: <?php 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; ?> When you use this function in singleton, mind there can by only one getInstance() call per line: <?php abstract class Singleton { ... } class MySingleton1 extends Singleton { ... } class MySingleton2 extends Singleton { ... } // this will work: $s1 = MySingleton1::getInstance(); $s2 = MySingleton2::getInstance(); // here will be problem: $s1 = MySingleton1::getInstance(); $s2 = MySingleton2::getInstance(); ?> --was-- A small correction on my last post. $matches[0] should be $matches[1]. Simplified version: <?php 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; ?> When you use this function in singleton, mind there can by only one getInstance() call per line: <?php abstract class Singleton { ... } class MySingleton1 extends Singleton { ... } class MySingleton2 extends Singleton { ... } // this will work: $s1 = MySingleton1::getInstance(); $s2 = MySingleton2::getInstance(); // here will be problem: $s1 = MySingleton1::getInstance(); $s2 = MySingleton2::getInstance(); ?> http://php.net/manual/en/function.get-called-class.php

« previous php.notes (#153581) next »