6

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();
Charles Bryant
  • 995
  • 2
  • 18
  • 30
  • Try adding the full namespace to the string class and see if it works like: "\\Foo\\Bar\\Variant". – Rainner Jan 14 '16 at 14:36
  • 2
    Fails = what error are you getting? – jedrzej.kurylo Jan 14 '16 at 14:39
  • @rainer I had tried several different combinations, but this works (SplitTest) is my namespace of the class $class = "\\SplitTest\\Variant" – Charles Bryant Jan 14 '16 at 14:45
  • Possible duplicate of [Laravel 5.1: Calling a function from string](http://stackoverflow.com/questions/34789209/laravel-5-1-calling-a-function-from-string) – lagbox Jan 14 '16 at 14:47
  • Possible duplicate of [PHP: Instantiating a class from a variable oddly fails](http://stackoverflow.com/questions/20908496/php-instantiating-a-class-from-a-variable-oddly-fails) – Havenard Jan 14 '16 at 14:54

2 Answers2

3

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
Charles Bryant
  • 995
  • 2
  • 18
  • 30
1

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.

PoX
  • 1,229
  • 19
  • 32