为什么我收到PHP致命错误:未捕获错误:找不到类’MyClass’?
作者:互联网
参见英文答案 > PHP static method call with variable class name and namespaces 2个
这有效:
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/C++ontainer.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
标签:php,oop,dependency-injection,namespaces,autoloader 来源: https://codeday.me/bug/20190611/1218763.html