I'm trying to update my project with namespaces.
Before using namespaces I could easily call a class via a variable like so:
<?php
$className = "Item";
$myClass = new $className();
?>
Now, when using namespaces (with use
) I'd expect this to work:
(not working allways meens: 'Can't find class' or smth like this)
<?php
namespace myProject
use myProject\Models
$className = "Item";
$myClass = new $className(); // this class has the namespace myProject\Models
// this doesn't work! (can't find class)
$myClass = new Models\$className();
// nope, doesn't work either
$myClass = new myProject\Models\$className();
// nope
?>
but calling the same class directly - without a variable - IS working
$myClass = new Item();
What I have to do, to make it work is:
<?php
namespace myProject;
use myProject\Models; // unnessecary now
$className = "\\" . __NAMESPACE__ . "\\Models\\" . "Item";
$myClass = new $className();
?>
My question now is:
If I want to call a class via a variable, do I really have to include the whole namespace as a fully qualified name?
EDIT:
I found myself an answer here:
Dynamic namespaced class with alias
I'll keep that question anyway, because I could not find the right answer in first place.