views:

50

answers:

1

Why i receive error? the class in the same namespace..

php 5.3.0

namespace ExampleSystem\Core;
class Test {
    public function __construct() {
     print 'Test ok';
    }
}

// Fatal error: Class 'Test' not found in ...
$class_name = 'Test';
$obj = new $class_name;

// Ok
$class_name = 'ExampleSystem\Core\Test';
$obj = new $class_name;

// Ok
$obj = new Test;
+2  A: 

I can't find chapter and verse in the PHP manual, but the obvious explanation is that when you do:

 $obj = new $string

then the value of $string is not mapped into the current namespace. This makes sense, when you consider that $string may have been passed in from somewhere else, where a different namespace may have been in effect.

Alnitak
i would have expected it to eval in the context of the namespace it's in but php rarely seems to do what i expect, and since i expect that now, can usually make it do what i want. :)
mtvee
Thanks!I found an example on the php.net site... Magic constant __NAMESPACE__ is the answer :)http://il2.php.net/manual/en/language.namespaces.nsconstants.phpExample 3
Alex