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?

1
  • 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. Commented Jan 21, 2011 at 0:22

3 Answers 3

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

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

Comments

1

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

more information here

1 Comment

Or even better using spl_autoload_register(). +1
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);
}

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.