Problem
Because this question appears to be a little hazy, I’ll use an example to clarify it:
$var = 'bar';
$bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()');
This is exactly what I intend to accomplish. How would you go about doing it? Of course, I could use eval() in the following way:
$var = 'bar';
eval('$bar = new '.$var.'Class(\'var for __construct()\');');
However, I’d rather avoid eval (). Is there a way to accomplish this without using eval()?
Asked by Pim Jager
Solution #1
First, create a variable for the classname:
$classname=$var.'Class';
$bar=new $classname("xyz");
This is something you’ll frequently find wrapped up in a Factory pattern.
For further information, see Namespaces and dynamic language features.
Answered by Paul Dixon
Solution #2
In my experience, I believe it’s important to point out that you must define the whole namespace path of a class (as far as I can tell).
MyClass.php
namespace com\company\lib;
class MyClass {
}
index.php
namespace com\company\lib;
//Works fine
$i = new MyClass();
$cname = 'MyClass';
//Errors
//$i = new $cname;
//Works fine
$cname = "com\\company\\lib\\".$cname;
$i = new $cname;
Answered by csga5000
Solution #3
You can use this code to pass dynamic constructor parameters to the class:
$reflectionClass = new ReflectionClass($className);
$module = $reflectionClass->newInstanceArgs($arrayOfConstructorParameters);
More details on dynamic classes and parameters may be found here.
With PHP 5.6, you can further simplify this by using Argument Unpacking:
// The "..." is part of the language and indicates an argument array to unpack.
$module = new $className(...$arrayOfConstructorParameters);
DisgruntledGoat was the one who pointed it up.
Answered by flu
Solution #4
class Test {
public function yo() {
return 'yoes';
}
}
$var = 'Test';
$obj = new $var();
echo $obj->yo(); //yoes
Answered by zalew
Solution #5
The call user func() and call user func arrayphp methods come highly recommended. They’re available here (call user func array, call user func).
example
class Foo {
static public function test() {
print "Hello world!\n";
}
}
call_user_func('Foo::test');//FOO is the class, test is the method both separated by ::
//or
call_user_func(array('Foo', 'test'));//alternatively you can pass the class and method as an array
If you want to send parameters to the method, use the call user func array() function.
example.
class foo {
function bar($arg, $arg2) {
echo __METHOD__, " got $arg and $arg2\n";
}
}
// Call the $foo->bar() method with 2 arguments
call_user_func_array(array("foo", "bar"), array("three", "four"));
//or
//FOO is the class, bar is the method both separated by ::
call_user_func_array("foo::bar"), array("three", "four"));
Answered by pickman murimi
Post is based on https://stackoverflow.com/questions/534159/instantiate-a-class-from-a-variable-in-php