Question

i'm trying to create a factory design pattern that will generate classes with a dynamic class name.

my code:

namespace FOO;

class MyFactory {
    public static function create($name) {
        return new \FOO\$name;
    }

}

I get a parsing syntax error (as netbeans indicated). is that possible or good practice? thanks

EDIT: parsing error: "unexpected variable name after \ expected identifier"

Was it helpful?

Solution

To instantiate classes with a variable name, you need to put the entire name, including namespace, into the variable:

$name = "Foo\\$name"; // note: no leading backslash
return new $name;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top