如何在yii中的两个同名类模型之间进行区分


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

我有两个模块。它们中的每一个都具有相同的模型类名。在模块文件中,我加载模型:

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

在我的例子中,mymodel和myanothermode有一个名称相同但功能不同的类(MyClass)。所以当我在控制器中的汽车模块中调用它时:

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

因此,它将始终采用application.modules.myanothermodel.models中的模型。他们之间有可能以某种方式产生分歧吗?

是的,有。甚至在纯PHP中也是如此。使用的命名空间

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();

此外,您还必须导入您使用的类(手动调用require或使用autoloading