3

I have string containing classname and an array of args.
$classname($args) works, but in this case I have only 1 argument in constructor
Anyone know, how to do this with args expanded?

guai
  • 780
  • 1
  • 12
  • 29

2 Answers2

7
$reflection = new ReflectionClass($classname);
$object = $reflection->newInstanceArgs($args);

http://php.net/reflection

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
  • Before reflection, I had this exact same problem. Know what I did? Generated a string and eval'd it. Disgusting. – erisco May 31 '11 at 20:02
  • yes, I don't see another solution without reflection too. However, when using interfaces, the factory-pattern (or such), something like this is usually not required. – KingCrunch May 31 '11 at 20:05
-1

Haha I just asked this question: PHP passing a class as a reference?

And you can't expand the $args. You could try passing $args[0], $args[1] etc.

Community
  • 1
  • 1
Pwnna
  • 9,178
  • 21
  • 65
  • 91