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();
5
  • Try adding the full namespace to the string class and see if it works like: "\\Foo\\Bar\\Variant". Commented Jan 14, 2016 at 14:36
  • 2
    Fails = what error are you getting? Commented Jan 14, 2016 at 14:39
  • @rainer I had tried several different combinations, but this works (SplitTest) is my namespace of the class $class = "\\SplitTest\\Variant" Commented Jan 14, 2016 at 14:45
  • Possible duplicate of Laravel 5.1: Calling a function from string Commented Jan 14, 2016 at 14:47
  • Possible duplicate of PHP: Instantiating a class from a variable oddly fails Commented Jan 14, 2016 at 14:54

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.