PHP Static variables – Object factory
On large busy projects where server resources do matter it is good idea to reuse object which is used several times during script execution in different scopes. There are more options.
One is to use global keyword on top of each function where object is needed but you must make always sure object really exist and take care about its creation if does not yet.
Another option is to create object and put it to $GLOBALS which creates some memory overhead and is somewhat ugly to use. On top of that if you don’t need the object always you have to care about its creation when needed again.
There is more elegant and efficient way to accomplish this task using static keyword and factory concept. Static keyword makes variable available in scope of factory method on all calls.
First you need to add static method for creating the object itself to your class.
/**
* factory method to create new object
* @return myObj
*/
public static function factory()
{
static $object;if(!is_a($object, get_class())) //makes sure object is created only once
$object = new self();return $object;
}
From now on anywhere in your code you use factory method to create object instead of direct object creation.
$newObj = myObj::factory();
Just one tip at the end, if your IDE suddenly doesn’t recognize what type the new object is and therefore it doesn’t suggest object variables and methods don’t forget to add momentary on top of factory method with defined return type.
Published by Stan Kuhn in: Advanced PHP Tips & Tricks

One Comments to “PHP Static variables – Object factory”
very interesting, thanks