1

I have 2 variables :

$class : contains the name of the class
$params : contains the parameters to initialize the class like ["key1" => "value1", "key2" => "value2"]

And I want to call a class like the function call_user_func() do with functions

ie :

$classObject = call_class($class, $params);
// Do the same that: 
$classObject = new $class("value1", "value2");

2 Answers 2

2

One option would be to use array argument unpacking, if you're running PHP >= 5.6:

$classObject = new $class(...$params);

Another would be to use Reflection

$reflection = new ReflectionClass($class);
$classObject = $reflection->newInstanceArgs($params);
Sign up to request clarification or add additional context in comments.

Comments

1

call_user_func_array lets you invoke the class methods.

<?php

class Foo {
  public function bar($param1, $param2) {
    echo $param1.$param2;
  }
}

$className = 'Foo';

call_user_func_array(array(new $className, 'bar'), array('Hello', 'World !'));

2 Comments

Your answer is right but the Mark Baker's answer is OOP
@ClémentLaffitte agreed.

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.