【问题标题】:Why can't I instantiate this class when using the classname and namespace?为什么在使用类名和命名空间时不能实例化这个类?
【发布时间】:2020-03-04 22:59:36
【问题描述】:

我有以下代码:

<?php
namespace Assessment;
class Database {

        private $server;
        private $username;
        private $password;
        private $database;

        public $conn;

        public function __construct()
        {           
            $this->server = "localhost";
            $this->username = "root";
            $this->password = "Museum2013";
            $this->database = "rest_test";

            $this->conn = mysqli_connect("$this->server","$this->username","$this->password","$this->database");

            if(!$this->conn)
            {
                echo "Database connection failed : " . mysqli_connect_error();;
            } 
        }
}

$database = new Assessment\Database;

?>

当我使用命名空间运行代码时,它不起作用。但是当我从顶部和对象中删除命名空间时,代码可以正常工作。我也想在子类中使用命名空间,但我不知道我的代码有什么问题。

【问题讨论】:

  • $database = use Assessment\Database;替换$database = new Assessment\Database;
  • 这不是错误,但页面没有加载,它说并返回 HTTP 错误 500。
  • 查看this,对你有帮助

标签: php class oop namespaces


【解决方案1】:

这是你的问题:

$database = new Assessment\Database;

由于类名存在于已声明命名空间的文件中(您的命名空间声明位于顶部),类名相对文件的命名空间(除非您使用完全限定类声明它们名称)。

该语句相当于尝试实例化Assessment\Assessment\Database

所以你可以简单地做:

$database = new Database();

它会起作用,因为它相当于实例化Assessment\Database

如果您想保留完全限定的类名,只需在前面加上 \ 以使 de 路径从根命名空间开始:

$database = new \Assessment\Database();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2014-09-04
    • 2017-05-02
    • 2014-06-20
    • 2013-11-18
    • 2019-01-15
    相关资源
    最近更新 更多