7

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.

Tomás Juárez
  • 1,517
  • 3
  • 21
  • 51
  • `use App\main` in `index.php` does nothing. `App\main` is a namespace, not a symbol name – Phil Jan 07 '14 at 00:15

1 Answers1

10

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.

Update

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.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • There's a way to replace this? I want to use Package\class instead of Package\class\class – Tomás Juárez Jan 07 '14 at 00:08
  • @TomiSebastiánJuárez They're your classes. If you want `Singleton` to be in the `App` namespace instead of the `App/Singleton` namespace, then simply change it. Same goes for `DataBase` in the `App/DataBase` namespace. – Phil Jan 07 '14 at 00:09