This works:
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
But when I try to break it out into individual files, I get an error.
PHP Fatal error: Uncaught Error: Class 'MyClass' not found in /nstest/src/Container.php:9
This is line 9:
static::$registry[$key] = new $key;
What's crazy is that I can hard code it, and it works, so I know the namespace is correct.
static::$registry[$key] = new MyClass;
hi
Obviously I don't want to hard code it because I need dynamic values. I've also tried:
$key = $key::class;
static::$registry[$key] = new $key;
But that gives me this error:
PHP Fatal error: Dynamic class names are not allowed in compile-time ::class fetch
I'm at a loss. Clone these files to reproduce:
.
├── composer.json
├── main.php
├── src
│ ├── Container.php
│ └── MyClass.php
├── vendor
│ └── ...
└── works.php
Don't forget the autoloader.
composer dumpautoload
{
"autoload": {
"psr-4": {
"scratchers\\nstest\\": "src/"
}
}
}
require __DIR__.'/vendor/autoload.php';
use scratchers\nstest\Container;
$obj = Container::get('MyClass');
echo $obj->prop;
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];
}
}
namespace scratchers\nstest;
class MyClass {
public $prop = 'hi';
}
Solution. Look for the undeclared variables as given in the error. If you are using inbuilt functions, ensure that there is no typo and the correct function is called. Check if the spellings are correct.
When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an " Uncaught Exception ... " message, unless a handler has been defined with set_exception_handler().
Thanks to @tkausl, I was able to get around dynamic relative namespacing by passing the fully qualified name in as the variable.
require __DIR__.'/vendor/autoload.php';
use scratchers\nstest\Container;
use scratchers\nstest\MyClass;
$obj = Container::get(MyClass::class);
echo $obj->prop;
hi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With