and would like to work with them effectively. Here is the premise for an application I am doing:
that said here is a function I am working on. It allows a class to be set, once, and be available globally anywhere. But it seems very clumsy and and I think there must be improvements in it:
function set_class_once(){
//example of most complex use: set_class_once('ClassA',$a [array], '$ginger', 'string');
$args=func_get_args();
if(!count($args))return;
$i=0;
$class='';
foreach($args as $n=>$v){
$i++;
if(!$class){
$class=$v; //always a string
unset($args[$n]); //remove from $args
continue;
}
if(is_array($v)){
$temp[$i]=$v;
$args[$n]='$temp['.$i.']'; //re-task
}else if(substr($v,0,1)=='$' && substr($v,1,7)!='GLOBALS'){
$args[$n]='$GLOBALS[\''.str_replace('$','',$v).'\']'; //variable
}else{
$args[$n]='\''.addslashes($v).'\'';
}
}
if(isset($GLOBALS[$class]) && is_object($GLOBALS[$class])){
//OK, we've instantiated that class
}else if(!class_exists($class)){
//fatal error
exit('Class '.$class.' does not exist');
}else{
print_r('$GLOBALS[$class]=new '.$class.'('.(!empty($args)?implode(',',$args):'').');').'<br>';
eval('$GLOBALS[$class]=new '.$class.'('.(!empty($args)?implode(',',$args):'').');');
}
}
class ClassC{
function ClassC($param1,$param2,$param3){
echo 'here is param1:<br>';
print_r($param1);
echo 'here is param2:<br>';
print_r($param2);
echo 'here is param3:<br>';
print_r($param3);
}
}
//with no params passed set_class_once('ClassA');
//with params passed:
$a=array(
'apple'=>'red',
'spinach'=>'green',
);
$ginger='fred backwards';
set_class_once('ClassC',$a,'$ginger','string');
Build yourself a simple singleton and extend it for the classes that you want to have only 1 instance:
class Singleton
{
public static function getInstance()
{
static $instance = null;
if (null === $instance) {
$instance = new static();
}
return $instance;
}
protected function __construct() { }
}
class ClassC extends Singleton
{
}
Then:
$object = ClassC::getInstance();
Not sure that I follow the args logic, but I'm sure there is a better practice for what you are attempting. Maybe create these with a factory class?