0

Is it possible to instantiate a class from a string, without declaring another variable before ?

It's usually done writing

$className = 'myClass'
$instance  = new $className();

but it could be handy to have it shorter like for example

$instance  = new ${'className'}();

The purpose is to have objects created (under condition) inside a loop without use of extra vars...

Edit : $className is dynamic, it is hard coded above to explain the situation

7
  • 2
    PHP 5.3 has some new syntax so it might work there. Another solution would be to use eval. Why do you have the 'no extra vars' constraint? Commented Jul 20, 2012 at 19:41
  • Also, if there is no variable with the class name in it, then you can just write $instance = new classname(); anyway. If you know the class name beforehand, you can hard code it; if you don't, it will already be in a variable. Perhaps you can expand your question further to explain your needs more clearly. Commented Jul 20, 2012 at 19:43
  • I don't get it. If you're not using a variable for it to be dynamic, and hard-coding 'className' string, why can't you just do new className() Commented Jul 20, 2012 at 19:43
  • Actually, first having a light code, and avoid memory overuse, because all of this use is already loops and heavy mySQL transactions Commented Jul 20, 2012 at 19:44
  • 1
    You should look for optimization somewhere else You're not likely to see any benefit from such actions but You can always unset the variable like @Panagiotis said if it really bothers You. Commented Jul 20, 2012 at 19:52

3 Answers 3

2

See factory pattern.

class Foo {
    static function factory($class, array $args = null) {
        return new $class($args);
    }
}

// class factoring; returns a new instance of requested class ($className)
Foo::factory($className);

I added optional arguments array if you want to set some class properties.

// pass some values for class constructor
Foo::factory($className, array('arg1' => 1, 'arg2' => 2, 'args3' => 3));

Furthermore, you can build "fluid" interfaces so you can "chain" methods when you use that pattern:

Foo::factory($className)->method1()->method2(array('param' => 'value'))->etc();

where method1(), method2() must return $this (the object itself) to chain multiple method calls in one line.

Sign up to request clarification or add additional context in comments.

Comments

1

You could make a factory function (or class/method) that takes a class name as a parameter, and then call it with the result of your dynamic PHP code that generates the string. You might consider it a bit cleaner but it's not going to save you any memory or speed.

class foo { }
function factory($class) { return new $class(); }

foreach (...) {
    $instance = factory(<some code that returns the string 'foo'>);
}

4 Comments

Except for memory usage which doesn't seem to be the real deal, this solution is interesting... I'm using this dynamic instantiation into different methods, so it may be a way to centralize it and have better control.
This example is wrong. factory should be a static method in foo and new class instantiated with foo. See the below example...
This is certainly not "wrong." While factories are classically implemented as a class (precisely the reason why I indicated "or class/method" in the answer) there is absolutely no syntactic or moral requirement to do so.
Also, you don't know what class is going to be instantiated, so you can't put the factory in the definition for that class. I.e., you'd have to create a new generic utility class that contains nothing but a universal factory method. That's no less "wrong" than my solution.
1

It's one extra variable, does it really make much of a difference? The answer is that unless you use eval (which comes with security issues) it isn't possible to do it any shorter than your first example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.