Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP dynamic class name laravel

I am using Laravel and having trouble creating a class with a string. The class is in the same name space of the class calling it.

The below code fails on the third line, I am unsure what I am doing wrong.

$class= "Variant";
$s = new Variant();
$nc = new $class();
like image 881
Charles Bryant Avatar asked Jan 14 '16 14:01

Charles Bryant


2 Answers

Ok the answer to this is I needed a namespace on the class.

In composer.json

"psr-4": {
    "SplitTest\\": "app/library/SplitTest/"
}

Then called the class as so:

$class= "//SplitTest//Variant";
$s = new Variant();
$nc = new $class();

If you to the psr-4 definition you will need to run

php artisan dump-auto
like image 149
Charles Bryant Avatar answered Oct 28 '22 17:10

Charles Bryant


This is actually what namespaces are for:

$s = new \OneNamespaceName\Variant();

This is often used in a Factory pattern. So namespaces are per-file so you need to include this in the the class declaration for Variant.

like image 36
PoX Avatar answered Oct 28 '22 18:10

PoX