Create class instance from within static method
Solution 1:
They way you're doing it is fine. There are a few other things that can make your life easier that you can do as well.
-
Don't hardcode the class name. If you're on 5.3+, use the keyword
static
. That way, if you extend the class, the new function can instantiate that one as well:public static function bar($var) { $obj = new static(); $obj->var = $var; return $obj; }
Then you can use it in any extending class without needing to override anything.
-
Figure out if
$var
should be passed in through a constructor rather than set after construction. If the object depends upon it, you should require it.public function __construct($var) { $this->var = $var; }
That way you can't instantiate the object without setting the variable.
-
Enforce the instantiation of the class through the static method. If you're doing anything in there that you need to do, then make the constructor either protected or private. That way, someone can't bypass the static method.
protected function __construct() {} private function __construct() {}
I hope that helps...
Edit: Based on your comment above, it sounds to me like you're trying to implement the Singleton Design Pattern. There's tons of information out there about why it's not a great idea and the bad things it may do. It has uses as well.
But there are a few other patterns that may be of use to you depending on what you're doing exactly.
- You can use the Factory Method if you're trying to create different objects using the same steps.
- If all of the objects start off the same and then are customized, you could use the Prototype Pattern.
- You could use an Object Pool if it's particularly expensive to create your object.
But one thing to consider, is that in PHP objects are pretty light weight. Don't try to avoid creating a new object just for that overhead. Avoid doing heavy things like database queries or filesystem accesses multiple times. But don't worry about calling new Foo()
unless foo
's constructor is particularly heavy...
Solution 2:
This looks like a simple factory method pattern.
You have a nice advantage: suppose that in the future you want to start using a different implementation (but that does the same thing). Using a factory you can change all the objects that are created in many places of a complex system simply by changing the creator method. Note that this would work easier if you used an external class (as is in the first link below).
Keeping it as you have now, you can also subclass this class and override the method to create a more complex object. I don't think this is what you want to achieve in here.
Anyway, this is good to enable Test Driven Development, abstraction and lots of other good things.
links:
- Php patterns
- Factory method pattern on wikipedia