Dynamic class name PHP laravel

I am using Laravel and cannot create a class with a string. The class is in the same space name of the class that calls it.

The following code does not work on the third line, I'm not sure what I'm doing wrong.

$class= "Variant";
$s = new Variant();
$nc = new $class();
+4
source share
2 answers

This is actually a namespace:

$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 class declaration for Variant.

+1
source

Ok, the answer to this question is: I need a namespace in the class.

In composer.json

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

Then called the class as follows:

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

psr-4,

php artisan dump-auto
+1

Source: https://habr.com/ru/post/1624290/


All Articles