Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP namespace confusion, class not found

Tags:

namespaces

php

I have two classes in the same folder in own files. But when I am trying to extends one to another it is giving namespace and class not found error.

Info: It is the first time I am extending class using namespace. Also nested namespace is new to me. DB\CRUD So may be I am doing completely wrong with namespace.

Error message:

Fatal error: Class 'DB\AT_Database' not found in /var/www/...

DB class

File: AT_Database.php

namespace DB;

class AT_Database
{
    ...
}

CRUD class

File: AT_CRUD.php

namespace DB\CRUD;


use DB\AT_Database;

class AT_CRUD extends AT_Database
{

    public function __construct()
    {

    }

}
like image 626
Code Lover Avatar asked Oct 20 '22 14:10

Code Lover


1 Answers

This may be silly mistake or may be I have overlooked it (which I should not as a programmer) and that is loading sequence of the class.

May be it's not worth to have as an answer but just adding so by chance in future it can help to someone who make such mistake.

As I mentioned in one of my comment, I am using glob to auto load all class files to include.

foreach ( glob( $this->classes_dir . "/*.php" ) as $class ) {
    include_once $class;
}

Now my file names are AT_CRUD.php and AT_Database.php. Here I realized that php loads files in alphabetical order. So when I extends AT_Database class into AT_CRUD its never found.

This is just because php loads AT_CRUD first than AT_Database so either I have to instantiate the class into or to use something like dependancy injection as @prehfeldt mention in his comment.

like image 197
Code Lover Avatar answered Oct 22 '22 02:10

Code Lover