Hello, I have a question I was wondering for a while, often when I find scrips for php or look at php frameworks I see a "registry class" or a "container class" which often holds variables or other objects utilizing the __get magic method.
Here is a oversimplified example of what I mean:
example 1:
class container {
private $objects;
public function __get($class){
if(isset($this->objects[$class])){
return $this->objects[$class];
}
return $this->objects[$class] = new $class();
}
}
the above example will have more functions to it when creating the class instead of just calling it but for my example it should be enough. "example 1" is how I mostly see it in scripts downloaded from the internet, it maintains a single class instance, now what I'm wondering is that wouldn't this example do the same thing and be more efficient:
example 2:
class simplecontainer {
public function __get($class){
return $this->$class = new $class();
}
}
But I never see "example 2" in other peoples scripts which makes me think twice before even considering to use it.
I tested container vs simplecontainer using several classes that they would contain and re-use around 100000 times and "example 1" does it in 0.75seconds on my local machine, and "example 2" does it in 0.29seconds.
So which should I use in my scripts? example 1 or example 2? and why?
thanks Mike and prodigitalson, you both deserve best answer here for approaching different issues with example 2.
edit: for example 2 to work like example 1 you MUST avoid defining any private or protected variables in simplecontainer and you need to make sure to never directly set any variables on the simplecontainer also there might be more quirks that have to do with it.
edit2: after further testing I have found out that in a real world full size application "example 2" provides no significant benefit to performance, with a little tweaking of example 1, example 2 is actually slower. I hope this provides some insight to someone other than me why example 2 is never used even though it is simpler looking.