Namespaced class not found

83 views Asked by At

I have the following which works just fine:

use frontend\models\modules\shipping\Usps;

$shipping = new Usps;

If however I use the following it throws the error: Class 'Usps' not found

use frontend\models\modules\shippingl\Usps;

I am loading classes dynamically, thus I cannot use the namespace when calling new $class, eg. I might also have:

use frontend\models\modules\payment\Usps;

$class = 'Usps';    
$shipping = new $class; 

How can I make this work using a variable? If I don't use namespaces/autoload and just include the class file it works just fine.

This question is not a duplicate, the referenced question/answers do not declare a 'use'.

1

There are 1 answers

0
Lin Meyer On

This is the only way I see this working without security issues and tons of errors, especially if $class coming from user input.

I added a "Ups" class so it makes a little more sense.

 use frontend\models\modules\payment\Usps;
 use frontend\models\modules\payment\Ups;

 if($class == 'Usps') {    
      $shipping = new Usps;
 } else if($class == 'Ups') {
      $shipping = new Ups;
 } else {
      // No valid class found - handle accordingly
 }