47

Is it possible to dynamically instantiate a class using a variable? For example is something like this possible in PHP?

class foo
{
    public $something;
}

$class_name = "foo";

$f = new $class_name();
Keith Davis
  • 351
  • 5
  • 14
Bijou Trouvaille
  • 8,794
  • 4
  • 39
  • 42
  • 36
    I disagree that this is not a real question. First of all it is grammatically a real question, secondly it has a definite answer with possibility of elaboration, thirdly it is easy to tell what is being asked, which is demonstrated by that fact that all the answers are essentially the same. While it is true that this, my first question on SO, was somewhat of a blunder, still to those who aren't able to randomly guess the correct syntax on their first try will benefit from a clear and searchable post on the subject. – Bijou Trouvaille Dec 04 '13 at 16:28

4 Answers4

45

That should work, yes.

You can also do:

$f = new $class($arg1,$arg2);
Chris Kloberdanz
  • 4,436
  • 4
  • 30
  • 31
10

Yes, this code will work fine.

Undo
  • 25,519
  • 37
  • 106
  • 129
timdev
  • 61,857
  • 6
  • 82
  • 92
4

In PHP 5 can I instantiate a class dynamically?

Yes you can, your code should work fine.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
2

Yes of course you can instantiate using dynamic names;

Muneer
  • 7,384
  • 7
  • 38
  • 62