From other posts, it looks like if you have a namespace and you want to dynamically create an object in a different namespace, you should build a string and use it in a new call. However, I get weird behavior. This method does not seem to work through namespaces.
User.php:
namespace application\models; class User { public function hello() { echo "Hello from User!"; } }
Controller.php:
namespace application\controllers; use application\models; require('User.php'); $userStr = 'models\\User'; //$userOne = new $userStr(); //Doesn't work. Gets a "Class 'models\User' not found" error $userOne = new models\User(); //Works fine $userStr = '\\application\\models\\User'; $userTwo = new $userStr(); //Works fine $userOne->hello(); $userTwo->hello();
Any idea why, when using a variable for a class name, I need to use a fully qualified namespace, when it is in a variable but hardcoded, can I use the use command?
source share