0

I have a function that does something similar to this:

function load_class($name){
  require_once('classes/'.$name.'.php');
  return new $name();
}

what I want to do is modify it so I can do something like this

function load_class($name, $vars = array()){
  require_once('classes/'.$name.'.php');
  return new $name($array[0], $array[1]);
}

The general gist of it is.

I want to be able to pass in an array of values that, gets used as the parameters for the class.

I dont want to pass in the actual array.

is this possible?

Hailwood
  • 89,623
  • 107
  • 270
  • 423
  • While the answer you accepted is certainly correct, I would encourage you anyway to look into class autoloading as indicated by bharath. From the code you provided it looks like you're overcomplicating things a bit. – Mchl Jan 21 '11 at 00:22

3 Answers3

2

Of course, it's called var args and you want to unpack them. http://php.net/manual/en/function.func-get-arg.php. Check out the examples... unpacking an array of arguments in php.

See Also How to pass variable number of arguments to a PHP function

Community
  • 1
  • 1
AbstractDissonance
  • 1
  • 2
  • 16
  • 31
1

if you are trying to load classes then you could use __autoload function

more information here

bharath
  • 1,233
  • 2
  • 11
  • 19
0

You can call functions this way with call_user_func_array, but in the case of a class constructor, you should use ReflectionClass::newInstanceArgs:

class MyClass {
   function __construct($x, $y, $z) { }
}


$class = new ReflectionClass("MyClass");

$params = array(1, 2, 3);

// just like "$instance = new MyClass(1,2,3);"
$instance = $class->newInstanceArgs($params);

Your code might look like this:

function load_class($name, $vars = array()){
  require_once('classes/'.$name.'.php');
  $class = new ReflectionClass($name);
  return $class->newInstanceArgs($vars);
}
user229044
  • 232,980
  • 40
  • 330
  • 338