Rohit
Rohit

Reputation: 3136

Chaining getting a class name to creating the class and calling a method?

I'm trying to figure out if this is a logic issue on my part or just a lack of knowledge.

I have a static method ConnectionFactory::getConnectionInterface($config['type']), which returns a string, a class name. That class has a method on it, createConnection. I'm trying to figure out if I can do it all in one line or not. I tried various things like

new {ConnectionFactory::getConnectionInterface($config['type'])}()->createConnection();

Switching the {} for (), adding them around the whole new, etc. I feel like I get closer in some parts, further in others.

I know I could just have the factory return a new instance of the object (and from my understanding, that may be the right way to do it?), but I'm hoping to figure out how I can write this code, or if I can't.

Upvotes: 0

Views: 25

Answers (1)

jfadich
jfadich

Reputation: 6348

You need to wrap the new object in ()

(new ConnectionFactory::getConnectionInterface($config['type'])())->createConnection();

Alternatively you could return an instance of the class instead of the class name.

public static function getConnectionInterface($type) {
    // generate class name $class

    return new $class()
}

Then use just use that object instead of creating a new instance when you call it.

$connection = ConnectionFactory::getConnectionInterface($config['type'])->createConnection()

Upvotes: 1

Related Questions