扩展没有命名空间的 class 时出现致命错误

Fatal error while extending a class which does not have namespace

我有两个 class,DatabaseStates。 class Database 没有分配命名空间。 class States,写在文件 states.php 中,其命名空间分配如下:

namespace Resources;      
require_once 'database.php';
  
$states = new States();
echo $states->readAll();

class States extends Database{
    private $db;
  
    public function __construct(){
      $this->db = new Database();
    }
  
    function readAll(){
      return $this->db->Execute('SELECT * FROM states;');
    }      
}

如果我输入 url http://localhost/mydomain/objects/states.php 应该实例化 class 和显示列表的状态,错误被抛出为:

Fatal error: Uncaught Error: Class 'Resources\Database' not found in C:\xampp\htdocs\mydomain\objects\states.php on line 5

如果我删除行 namespace Resources; 代码运行。

我最近决定在我的网站中实施命名空间,所以很可能是我做错了什么。

有什么帮助吗?

PHP 手册有 a section introducing namespaces which is well worth reading. In particular, have a look at this page drawing the analogy to a file system:

The same principle can be applied to namespaced elements in PHP. For example, a class name can be referred to in three ways:

  1. Unqualified name, or an unprefixed class name like $a = new foo(); or foo::staticmethod();. If the current namespace is currentnamespace, this resolves to currentnamespace\foo. If the code is global, non-namespaced code, this resolves to foo.
  2. Qualified name, or a prefixed class name like $a = new subnamespace\foo(); or subnamespace\foo::staticmethod();. If the current namespace is currentnamespace, this resolves to currentnamespace\subnamespace\foo. If the code is global, non-namespaced code, this resolves to subnamespace\foo.
  3. Fully qualified name, or a prefixed name with global prefix operator like $a = new \currentnamespace\foo(); or \currentnamespace\foo::staticmethod();. This always resolves to the literal name specified in the code, currentnamespace\foo.

在您的示例中,Database 是一个“不合格的名称”,因此第 1 点适用。当前的命名空间是Resources,所以它指的是Resources\Database。如果删除 namespace Resources; 行,代码将变为“全局、非命名空间代码”,因此它仅引用 Database.

要在当前命名空间为Resources时引用class Database,您可以使用“完全限定名称”,如第3点所述。所以在这种情况下, 你会写 class States extends \Database.

还有其他写法,比如adding use statements to import/alias a name,但是我在这里复制整个PHP手册没有意义。