We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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?



58.4k

please upload code file auth.php ?



7.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?

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


98.9k

See Example #3

https://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?

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