Alex
Alex

Reputation: 73

Namespace and classes in php

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;

Upvotes: 1

Views: 266

Answers (1)

Alnitak
Alnitak

Reputation: 339816

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.

Upvotes: 2

Related Questions