Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespaces and traits

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.

like image 610
Tomás Juárez Avatar asked Jan 06 '14 23:01

Tomás Juárez


1 Answers

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.

like image 107
Phil Avatar answered Sep 30 '22 11:09

Phil