简体   繁体   中英

How can I make a diferrence between 2 class model with the same name in yii?

I have two modules. Each of them have the same model class name. In the Module file I load the model:

  $this->setImport(array(
            'cars.models.*',
            'cars.components.*',
            'application.modules.mymodel.models.*',
            'application.modules.myanothermodel.models.*',
        ));
    }

In my case the mymodel and myanothermodel have a class with the same name ( MyClass ) but different functionalities. So when i called it in my cars module in controller:

$mymodel = MyClass::model()->find('month = :month and year = :year and user_id = :user', array('month' => $month, 'year' => $year, 'user' => $user->id));

As result it will always take the model from application.modules.myanothermodel.models . Is is possible to make somehow a diferrence between them ?

Yes, there is. And even in pure PHP. Use namespaces for that

namespace models\mymodel\models;

class MyClass {}

namespace models\myanothermodel\models;

class MyClass {}

class AnotherClass {
    $classA = new \models\myanothermodel\models\MyClass();

/* or */

use \models\myanothermodel\models\MyClass;

class AnotherClass {
    $classA = new MyClass();

Also you have to import class that you use (manually calling require or using autoloading )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM