Ajmal Razeel
Ajmal Razeel

Reputation: 1701

Why can't I instantiate this class when using the classname and namespace?

I have the following code:

<?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;

?>

When I run the code with the namespace, it does not work. But when I remove the namespace from top and in object then the code works fine. I also want to use the namespace in child class but I don't know what is wrong with my code.

Upvotes: 0

Views: 49

Answers (1)

yivi
yivi

Reputation: 47329

This is your problem:

$database = new Assessment\Database;

Since the class name exists in a file with declared namespace (your namespace declaration at the top), class names are relative to the namespace of the file (unless you declare them with the fully qualified class name).

That statement was the equivalent of trying to instanstiate Assessment\Assessment\Database.

So you can simply do:

$database = new Database();

And it will work, since it would be the equivalent of instantiating Assessment\Database.

If you want to keep the fully qualified class name, just prepend a \ to make de path start from the root namespace:

$database = new \Assessment\Database();

Upvotes: 1

Related Questions