Namespaces and traits

12,841

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.

Share:
12,841
Tomás Juárez
Author by

Tomás Juárez

Systems Engineer. Born and raised in Tandil city.

Updated on August 09, 2022

Comments

  • Tomás Juárez
    Tomás Juárez over 1 year

    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.