Often in order to use a class method, we create an instance at each usage location. In this way, objects are created repeatedly which results in performance degradation. This developer tip will help you in reusability of already created class instance.
/**
* Create instance of a class.
* If already created, use it.
*/
class ocObjectInstance {
function getObjectInstance($class_name, $params = NULL, $namespace = '') {
$object_name = md5($class_name . "_" . serialize($params). serialize($namespace));
if(!class_exists($namespace . $class_name)){
return;
}
if (!is_array($params) && !is_null($params)) {
$params = array($params);
}
if (isset($GLOBALS[$object_name])) {
return $GLOBALS[$object_name];
}
$refClass = new \ReflectionClass($namespace . $class_name);
if (is_null($params)) {
$GLOBALS[$object_name] = $refClass->newInstanceArgs();
}
else {
$GLOBALS[$object_name] = $refClass->newInstanceArgs($params);
}
return $GLOBALS[$object_name];
}
}
Here, once object instance is created it gets preserved in the global variable. On next object creation, its presence is checked and if it is found, existing instance is returned.
class firstClass {
public function __construct() {
print "creating instance";
}
function addTwo($a = 0, $b = 0) {
$sum = intval($a) + intval($b);
return $sum;
}
}
$objFirst = ocObjectInstance::getObjectInstance('firstClass');
class firstClass {
public function __construct($a, $b) {
$sum = intval($a) + intval($b);
print $sum;
}
function addTwo($a = 0, $b = 0) {
$sum = intval($a) + intval($b);
return $sum;
}
}
$objFirst = ocObjectInstance::getObjectInstance('firstClass', array(20,25));
namespace first;
class firstClass {
public function __construct($a, $b) {
$sum = intval($a) + intval($b);
print $sum;
}
function addTwo($a = 0, $b = 0) {
$sum = intval($a) + intval($b);
return $sum;
}
}
$objFirst = ocObjectInstance::getObjectInstance('firstClass', array(20,25),'\\first\\');