Yii2从类中访问类

时间:2018-06-18 08:23:33

标签: yii2

我正在尝试使用我想要搜索的类中的findOn。这有可能还是有更好的方法?

class CmsSettings extends ActiveRecord
{

   public static function tableName()
   {
       return 'cms_settings';
   }

   //not working
   public static function run(){

       $results = CmsSettings::findOn(1):

       return $results;

   }

   // not working
   public static function check(){

       $results = CmsSettings::findOn(1):

       if($results->somesetting){
          return true;
       }

   }
}

2 个答案:

答案 0 :(得分:2)

您应该使用static::findOne(1)。通过使用selfCmsSettings,您只需对返回类型进行硬编码,这会使此类变得不那么灵活,并且会在继承时给您带来意想不到的结果。例如,如果您创建扩展您的类的子模型:

class CmsSettings extends ActiveRecord {

    public static function run() {
        $results = CmsSettings::findOne(1);

        return $results;
    }

    // ...
}

class ChildCmsSettings extends CmsSettings {

}

您希望ChildCmsSettings::run()将返回ChildCmsSettings的实例。错了 - 你会得到CmsSettings。但是如果使用static编写此方法:

public static function run() {
    $results = static::findOne(1);

    return $results;
}

您将获得用于通话run() - ChildCmsSettings的课程实例。

答案 1 :(得分:1)

使用self

参考findOne()

class CmsSettings extends ActiveRecord
{
   public static function tableName()
   {
      return 'cms_settings';
   }

   public static function run() 
   {
      $results = self::findOne(1);
      return $results;
   }

   public static function check() 
   {
      $results = self::findOne(1);

      if ($results->somesetting) {
         return true;
      }

   }
}