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?
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;
class MyProject{
public static function execute(){
include ('database.php');
$pdo = database::connect();
}
}
More: http://php.net/manual/en/language.namespaces.importing.php
See the global space section of namespaces. You would need to precede any class calls within the global space with a backslash. In your case:
$pdo = \database::connect();