Security Notice Due to the insecurity of allowing an end user to instantiate any class through this method, I highly recommend against doing this and following my example at the bottom.
Class imports are not evaluated at runtime. You'd have to use the full path to the class to dynamically instantiate it as illustrated in this example:
<?php
namespace One {
use Two\B;
class A {
function __construct($className) {
echo "Attempting to construct $className..";
new $className;
}
}
new A(B::class); // Works since the B import is evaluated before runtime.
try {
new A("B"); // Doesn't work since "B" is not evaluated until runtime
}
catch (\Throwable $e) {
echo $e->getMessage() . "\n";
}
new A("Two\B"); // Works since you use the full path to B.
}
namespace Two {
class B {
function __construct() {
echo "B constructed!\n";
}
}
}
https://3v4l.org/LTdQN
While you could do this, that's asking for trouble. What would stop someone from retrieving data out of some model they shouldn't have access to?
Instead, build up an array of available classes and let them pass the array key instead of passing the name of the class.
$classes = [
'a' => AAA::class,
'b' => BBB::class,
'c' => CCC::class,
];
// $from_input being a, b, or c
if (isset($classes[$from_input])) {
$obj = new $classes[$from_input];
}