Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Unable to instantiate variable class

So I have 2 classes, let's call them AuthOne and AuthTwo, and depending on the incoming request, I want to be able to init either one on the fly. So in my auth.php, I check the request (edited for brevity):

use Sandbox\Auth\AuthOne;
use Sandbox\Auth\AuthTwo;

$auth = 'Auth' . ucfirst($this->request->getPost('auth'));
$oAuth = new $auth();

but this doesn't work, I get an error

PHP Fatal error: Class 'AuthOne' not found in .... /sandbox/app/library/auth/auth.php ....

however, if I simply just do:

$oAuth = new AuthOne();

or

$oAuth = new AuthTwo();

this works fine! And I've checked to make sure that $auth does indeed equals AuthOne or AuthTwo and as you can also see in the error message. What am I doing wrong?



36.3k

please upload code file auth.php ?



5.9k
Accepted
answer

have you tried full namespace?

$auth = 'Sandbox\\Auth\\' . 'Auth' . ucfirst($this->request->getPost('auth'));
$oAuth = new $auth();
edited Nov '14

Well that works, thanks! But for my 411, can someone please explain to me why it couldn't find the class without specifying the full namespace?

have you tried full namespace?

~~~php $auth = 'Sandbox\Auth\' . 'Auth' . ucfirst($this->request->getPost('auth')); $oAuth = new $auth(); ~~~



84.5k

See Example #3

http://php.net/manual/en/language.namespaces.importing.php

Well that works, thanks! But for my 411, can someone please explain to me why it couldn't find the class without specifying the full namespace?

have you tried full namespace?

~~~php $auth = 'Sandbox\Auth\' . 'Auth' . ucfirst($this->request->getPost('auth')); $oAuth = new $auth(); ~~~