gpt4 book ai didi

php - 为什么我会收到 PHP fatal error : Uncaught Error: Class 'MyClass' not found?

转载 作者:可可西里 更新时间:2023-11-01 13:44:46 24 4
gpt4 key购买 nike

<分区>

这个有效:

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/"
}
}
}

主.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';
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com