简体   繁体   English

命名空间和特征

[英]Namespaces and traits

I'm getting an error using traits and namespaces, beacuse the trait can not be found. 我使用特征和命名空间时出错,因为无法找到特征。

index.php: index.php文件:

require_once 'src/App.php';
use App\main;

$App = new App();

src/App.php SRC / App.php

namespace App\main;
require_once __DIR__ . DIRECTORY_SEPARATOR . 'DataBase.php';
/**
 * code
 */

src/DataBase.php 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 SRC / Singleton.php

namespace App\Singleton.php;
trait Singleton {
  /**
   * code
   */
}

But, when I run that from Index.php, I'm getting this error: 但是,当我从Index.php运行它时,我收到此错误:

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: Php自动在命名空间中设置类名,例如:

Bar.php 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. 当您调用此包时,可以使用App \\ Bar,这意味着默认情况下会设置类。

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. 您没有在App\\DataBase命名空间中导入(或在PHP 用法中使用 -ing) App\\Singleton\\Singleton符号,因此PHP假定Singleton位于同一名称空间中。

In src/DataBase.php ... 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. 此外,我强烈建议您实施自动加载器策略(最好是PSR-0)以避免所有require_once调用。

Update 更新

To clarify, when you do this... 澄清一下,当你这样做时......

namespace App\DataBase;

class DataBase { ... }

The full name of this class is \\App\\DataBase\\DataBase . 该类的全名是\\App\\DataBase\\DataBase The namespace declaration does not include the class / trait names. namespace声明不包括类/特征名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM