DonOfDen
DonOfDen

Reputation: 4098

Using PHP Namespace in hierarchy directory structure Error

I am working with a folder structure as follows:

classes
    -common.php
    -core.php
modules
    -index/index.php

I am trying to use the common.php in my index.php file and I am facing error:

Fatal error: Class 'classes\Common' not found in D:\xampp\htdocs\devmyproject\modules\index\index.php on line 7

My Code:

commom.php class:

**Directory:/root/classes/common.php**
<?php
namespace classes;

class Common
{

    function __construct()
    {

    }
}

My index.php file which try to use the classes/commom.php

**Directory:/root/modules/index/index.php**
<?php
namespace modules\beneficiary;
use \classes as hp; 
include_once 'config.php';
$common = new \classes\Common();
//To Get Page Labels
$labels = $common->getPageLabels('1');

I am includeing common.php in config.php

$iterator = new DirectoryIterator($classes);
foreach ($iterator as $file) {
    if ($file->isFile())
        include_once 'classes/' . $file;
}

My Try:

It works fine when I use the folder structure as follows:

classes
    -common.php
    -core.php
modules
    -index.php

If I use another folder inside modules it get error? I am not sure about he hierarchy of folders when using namespace can some one help me?

Upvotes: 0

Views: 3247

Answers (1)

Oswald
Oswald

Reputation: 31685

You have to either include common.php in index.php (better: use one of its relatives include_once or require_once) or set up an autoloader using spl_autoload_register() (or, not recommended, writing an __autoload() function).

Upvotes: 2

Related Questions