I'm just curious as to if creating an object on the fly is possible in PHP. I thought I'd seen it done before. Of course I can just assign it to a variable but just wondering if this possible.
new className()->someMethod();
Of course this throws a syntax error, so obviously it's not done like that (if it's even possible). Should I just assign it to a variable, as I really have no problems with doing that I was just curious?
Just some further details. Static methods aren't really an option as the class I was trying to do this for was PHPs ReflectionMethod class.
this usage is typical in Java but is not available before PHP 5.3. And now it is a new feature in PHP 5.4. Pls check PHP 5.4 new features. And the usage should be:
(new Foo)->bar()
This only works if you are using a singleton-pattern for instanciating the object. If you are not aware of how to implement the singleton-pattern, you'll have to search around the web. But this way it would work:
className::getInstance()->someMethod();
EDIT
As stated by zerkms a factory-method would also be possible:
class ReflectionFactory
{
public static function factory($arguments)
{
return new ReflectionClass($arguments);
}
}
// Then in your code for example
ReflectionFactory::factory()->getConstants();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With