I'm getting an error using traits and namespaces, beacuse the trait can not be found.
index.php:
require_once 'src/App.php';
use App\main;
$App = new App();
src/App.php
namespace App\main;
require_once __DIR__ . DIRECTORY_SEPARATOR . 'DataBase.php';
/**
* code
*/
src/DataBase.php
namespace App\DataBase;
require_once __DIR__ . DIRECTORY_SEPARATOR . 'Singleton.php';
class DataBase {
use Singleton; // or use App\Singleton
/**
* code
*/
}
src/Singleton.php
namespace App\Singleton.php;
trait Singleton {
/**
* code
*/
}
But, when I run that from Index.php, I'm getting this error:
Fatal error: Trait 'App\DataBase\Singleton' not found in (...)
How can I fix it?
EDIT
Php automatically set the class name in the namespace, for example:
Bar.php
namespace App;
class Bar {
/**
* code
*/
}
The, when you call this package, you can use App\\Bar, this means that the classes is setted by default.
You aren't importing (or use -ing in PHP parlance) the App\\Singleton\\Singleton
symbol in your App\\DataBase
namespace so PHP assumes that Singleton
is in the same namespace.
In src/DataBase.php
...
namespace App\DataBase;
use App\Singleton\Singleton;
require_once __DIR__ . '/Singleton.php';
class DataBase {
use Singleton;
// and so on
Also, I highly recommend you implement an autoloader strategy (preferably PSR-0) to avoid all the require_once
calls.
To clarify, when you do this...
namespace App\DataBase;
class DataBase { ... }
The full name of this class is \\App\\DataBase\\DataBase
. The namespace
declaration does not include the class / trait names.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.