user1929946
user1929946

Reputation: 2503

Instantiating class from string wont really work in php

Ive just started learning namespaces. If I do this:

$a = new Devices\Desktop();

this works. But I have dynamic class names, so I have to do it from a variable.

$a = 'Devices\Desktop';
$a = new $a();

this is not working, although its the same. The class is not found. Why?

Upvotes: 0

Views: 103

Answers (1)

deceze
deceze

Reputation: 522626

Going out on a limb:

namespace Foo;

class Bar { }

new Bar;

$bar = 'Bar';
new $bar;

This won't work. String class names are always absolute, they're not resolved relative to the current namespace (because you can pass strings from one namespace to another, which should it resolve against then?). To make those two instantiations equivalent, you need to use a fully qualified class name:

$bar = 'Foo\Bar';

The __NAMESPACE__ constant can be useful here:

$bar = __NAMESPACE__ . '\Bar';

Upvotes: 3

Related Questions