Reputation: 11117
I need to create classes based on the parameter passed to a function. I do it this way:
public function index($source)
{
if(in_array($source, ModuleManager::getAllModules()))
{
$provider = new $source();
if($image)
{
return $provider->getAll(true);
}
else
{
return $provider->getAll(false);
}
}
}
Notice that on line 5 I'm trying to create an object of class $source
which will definitely be available. I understand that the above code is actually an eval
call. I'm using Laravel 5.2 and the above code returns:
FatalThrowableError in ProcReqController.php line 19:
Fatal error: Class 'Example' not found
In the above error Example
can be any class that I made. Now if I hard code the value of $source
then it works just fine.
What am I getting that error?
Upvotes: 8
Views: 5441
Reputation: 3873
The autoloader allows you to use classes without fully qualifying them... in the php interactive shell you'll have to manually include classes AND fully qualify them.
if you have a composer project, go to it's directory and do the following to load the Primal color classes:
set_include_path(getcwd().'/vendor/primal/color/lib/Primal/Color/');
include 'Color.php';
include 'Parser.php';
include 'RGBColor.php';
include 'HSVColor.php';
$hello = Primal\Color\Parser::parse('#666');
var_export($hello->toHSV());
/*
returns
Primal\Color\HSVColor::__set_state(array(
'hue' => 0,
'saturation' => 0,
'value' => 37.647058823529413,
'alpha' => 1,
))
*/
Upvotes: 0
Reputation: 33058
I believe what's happening is PHP gets confused when you try to instantiate a class whose class name is in a variable and it has to do with imports.
Set your $class
variable to the fully qualified class name including the namespace and it should work.
In this way, new $class()
should work even while including parenthesis.
After further testing, it seems when you instantiate a variable class, it always assumes global namespace.
With this in mind, you can use class_alias
to alias each of your classes. In config/app.php
, you can add each class to the aliases
array.
'aliases' => [
....
'Example' => App\Example::class
]
Upvotes: 10
Reputation: 1204
Remove the parentheses at the end of the instantiation call, I think.
Check out this php interactive shell session:
php > class Foo { };
php > $fooname = 'Foo';
php > $bar = new $fooname;
php > var_dump($bar);
object(Foo)#2 (0) {
}
src: https://stackoverflow.com/a/4578350/2694851
Upvotes: -2