A
A
atis //2015-11-23 14:21:00
PHP
atis //, 2015-11-23 14:21:00

Why is the class called twice in the autoloader?

namespace base\libs;

class User
{
  use patterns\Singleton;

  public function getData()
  {

  }
}

namespace base\patterns;

trait Singleton
{
  static private $instance;

  private function __construct() {}
  private function __clone() {}
  private function __wakeup() {}

  static public function getInstance()
  {
    if (empty(static::$instance)) {
      static::$instance = new static();
    }

    return static::$instance;
  }
}

namespace base;

$User = libs\User::getInstance();
$User->getData();

when executing this code, autoloader is called 3 times!
1. base\libs\User
2. base\patterns\Singleton
3. Singleton !!!
I can not understand in any way when the 3rd request is called?
PS Even if I change use patterns\Singleton;to use \base\patterns\Singleton;I still have 3 calls.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Denis, 2015-11-23
@atis2345

// dir /base/libs/';
namespace base\libs;

// file /base/libs/User.php';
class User
{
    // file /base/libs/patterns/Singleton.php';
    use patterns\Singleton;
    //.. 
}

// dir /base/patterns/';
namespace base\patterns;

// file /base/patterns/Singleton.php';
trait Singleton
{
    //.. 
}


// dir /base/';
// file /base/AnyFile.php';
namespace base;

$User = libs\User::getInstance();
// include /base/libs/User.php;
//                      ^
//                      | 200 Ok
//                      +--------
// call User::getInstance
// include /base/libs/patterns/Singleton.php;
//               ---
//                ^
//                | (Вторая строка "2. base\patterns\Singleton")
//                | 404 Not Found. 
//                | 
//                | Далее попытка загрузить из глобального namespase
//                | include \Singleton
//                | (третья строка "3. Singleton !!!")
//                +-------------------------------------------------
//                
// 
// $User->getData();
// 500 Internal Server Error

/base/patterns/Singleton.php is the real path.
/base /libs/patterns/Singleton.php is included.
Please do not ignore the answer of Mikhail Osher

M
Mikhail Osher, 2015-11-23
@miraage

Do you have it all in one file? Uuuu, I beg you....
https://getcomposer.org/doc/04-schema.md#autoload
And in general, carefully read all the PSR standards.

A
Alexey Ukolov, 2015-11-23
@alexey-m-ukolov

I don't know if this is related to the problem, but it should be like this:
use base\patterns\Singleton;

A
Andrey Degtyaruk, 2015-11-23
@hlogeon

I think according to this:
Try instead use patterns\Singleton;
Write use base\patterns\singleton;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question