Why am I getting PHP Fatal error: Uncaught Error: Class 'MyClass' not found?

Why am I getting PHP Fatal error: Uncaught Error: Class 'MyClass' not found?

这个有效:

class MyClass {
    public $prop = 'hi';
}

class Container {
    static protected $registry = [];
    public static function get($key){
        if(!array_key_exists($key, static::$registry)){
            static::$registry[$key] = new $key;
        }
        return static::$registry[$key];
    }
}

$obj = Container::get('MyClass');
echo $obj->prop;

hi

但是当我尝试将其分解为单独的文件时,出现错误。

PHP Fatal error: Uncaught Error: Class 'MyClass' not found in /nstest/src/Container.php:9

这是第 9 行:

static::$registry[$key] = new $key;

疯狂的是我可以对其进行硬编码,而且它可以工作,所以我知道命名空间是正确的。

static::$registry[$key] = new MyClass;

hi

显然我不想对其进行硬编码,因为我需要动态值。我也试过:

$key = $key::class;
static::$registry[$key] = new $key;

但这给了我这个错误:

PHP Fatal error: Dynamic class names are not allowed in compile-time ::class fetch

我很茫然。 Clone these files to reproduce:

.
├── composer.json
├── main.php
├── src
│   ├── Container.php
│   └── MyClass.php
├── vendor
│   └── ...
└── works.php

别忘了自动装弹器。

composer dumpautoload

composer.json

{
    "autoload": {
        "psr-4": {
            "scratchers\nstest\": "src/"
        }
    }
}

main.php

require __DIR__.'/vendor/autoload.php';
use scratchers\nstest\Container;

$obj = Container::get('MyClass');
echo $obj->prop;

src/Container.php

namespace scratchers\nstest;

class Container {
    static protected $registry = [];
    public static function get($key){
        if(!array_key_exists($key, static::$registry)){
            static::$registry[$key] = new $key;
        }
        return static::$registry[$key];
    }
}

src/MyClass.php

namespace scratchers\nstest;

class MyClass {
    public $prop = 'hi';
}

Thanks to @tkausl,我能够通过将完全限定名称作为变量传递来绕过动态相对命名空间。

require __DIR__.'/vendor/autoload.php';
use scratchers\nstest\Container;
use scratchers\nstest\MyClass;

$obj = Container::get(MyClass::class);
echo $obj->prop;

hi