Lacrifilm Lacrifilm - 1 month ago 7
PHP Question

Include inside namespace not found

I have 3 files inside a folder:

index.php

<?php

include ('MyProject.php');

$controller = new MyProject\MyProject();
$controller::execute();

?>


MyProject.php

<?php

namespace MyProject;

class MyProject{

public static function execute(){
include ('database.php');
$pdo = database::connect();
}

}

?>


database.php

<?php

class database{

public static function connect(){
return 'connect';
}
}

?>


Why when I include
database.php
inside
myproject.php
, php shows the following error:


Fatal error: Class MyProject/database not found in ...


In my case I don't want to add
namespace
in
database.php
, why this is happening and how can I solve this problem?

Answer

Included files don't inherit of namespace. So your database object is related to the global namespace, which is \. To call it inside another namespace, use the use statement or add the global namespace \ before the class name :

\database::connect();

Or

namespace MyProject;

use \database as database;

class MyProject{
    public static function execute(){
        include ('database.php');
        $pdo = database::connect();
    }
}

More: http://php.net/manual/en/language.namespaces.importing.php