Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create objects on the fly without variable assignment with PHP

Tags:

object

php

class

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.

like image 758
Jason Lewis Avatar asked Jul 04 '11 05:07

Jason Lewis


2 Answers

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()
like image 179
zhihong Avatar answered Sep 23 '22 23:09

zhihong


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();
like image 29
Fidi Avatar answered Sep 23 '22 23:09

Fidi