-1

Possible Duplicate:
Is there a call_user_func() equivalent to create a new class instance?

I instansiate my class like this:

$className = 'varClassName';
$validator = new $className;

But I want to pass an array as an argument to the class constructor. I thought the following might work:

$className = 'varClassName(array('min'=>2, 'max'=50))';
$validator = new $className;

However this results in an error that the class cannot be found. So how can I pass args to a class constructor while using variable class name?

Community
  • 1
  • 1
Owen
  • 7,347
  • 12
  • 54
  • 73
  • This is not possible without eval(). Why do you need it? It smells of a design flaw – Pekka Dec 01 '11 at 09:56
  • It's possible without `eval()`. See below. But I agree that this clearly indicates a design flaw. And a major one at that. – Till Helge Dec 01 '11 at 09:58

3 Answers3

2

Have a look at ReflectionClass. You can do something like this:

$rc = new ReflectionClass("YourClass");
$obj = $rc->newInstanceArgs(array(...));

This is probably the best way to do this, but it's a fairly new addition to PHP. The alternative would be to use eval() but I refuse to write code like this. ;)

Till Helge
  • 9,253
  • 2
  • 40
  • 56
0

You do like this: $validator = new $className($array);

Mārtiņš Briedis
  • 17,396
  • 5
  • 54
  • 76
0
$className = 'varClassName';
$validator = new $className(array('min'=>2, 'max'=>50));
Carsten
  • 17,991
  • 4
  • 48
  • 53
  • I'm not sure whether this is really what the OP's asking for. But we will see – Pekka Dec 01 '11 at 10:29
  • This is not even possible in PHP, I wonder why the OP did accept this as an answer - an even got three upvotes. *"Parse error: syntax error, unexpected '=', expecting ')'"* - this is fatal - see: http://eval.in/3599 – hakre Nov 16 '12 at 13:52
  • Sorry, I didn't notice befor that I've made a typo (in the array definition, I wrote `=` instead of `=>`). Now it works. Thank you for noticing. :) – Carsten Nov 16 '12 at 15:44