1

I'm trying to make a object of a class from another file. Both file is located in the same folder & I used 'namespace App' in the both files. In the login files I'm trying to get the class object but it couldn't find the class. Codes are given below.

Database Class : 'Database.php'

<?php
    namespace App;

    require_once 'config.php'; 

class Database{

    private $db;

    public function __construct(){

        $this->db =  new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    }

    public function getConnection(){

        return $this->db;

    }

login.php file :

<?php

    namespace App;

    use App\Database; 

    require_once 'config.php'; 


    $DB = new Database(); 

    $con = $DB->getConnection;

When I execute login.php , it says Fatal error: Uncaught Error: Class 'App\Database' not found in login.php on line 10

1
  • 1
    use Database; if you're in the same \App namespace as the class you're using. Commented Dec 4, 2017 at 13:38

3 Answers 3

3

I think you missing to require database file. Also, call the method by the following way. You are calling a property getConnection that is not available.

<?php
namespace App;
require_once 'config.php';
require_once 'Database.php';

use App\Database;

$DB = new Database();
$con = $DB->getConnection();
Sign up to request clarification or add additional context in comments.

6 Comments

So, I've to require the files always event though I use namespace?
Yeah @MisbahAhmad
Is there any way to avoid require?
@MisbahAhmad YES: Use a PHP Autoloader
If you don't want to use require each time then use php's spl_autoload_register() function to automatically call classes @MisbahAhmad
|
2
  • If you are in the root namespace:

use \App\Database; You want to tell PHP to search for App namespace in the namespace root, if that's where it is.

  • If you are in the App namespace:

use Database; You want to tell PHP to search for Database in the current namespace, if that's where it is.

  • If you are in another namespace:

If you're in another namespace (such as \Blob) then reference from the root, \App\Database, as above.


namespace App;

use App\Database; 

This is currently looking for \App\App\Database and so is telling you that App\Database is not found in the \App namespace.

Comments

0

If you are referencing the namespace in:

namespace App;

You do not need to then include the namespace in the 'use'.

namespace App;
use Database;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.