user759235
user759235

Reputation: 2207

Yii2 access class from within the class

I'm trying to use the findOn from within the class that I want to search. Is this possible or is there a better way?

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;
       }

   }
}

Upvotes: 1

Views: 44

Answers (2)

rob006
rob006

Reputation: 22174

You should probably use static::findOne(1). By using self or CmsSettings you are just hardcoding returned type, which makes this class less flexible and will give you unexpected results on inheritance. For example if you create child model which extends your class:

class CmsSettings extends ActiveRecord {

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

        return $results;
    }

    // ...
}

class ChildCmsSettings extends CmsSettings {

}

You expect that ChildCmsSettings::run() will return instance of ChildCmsSettings. Wrong - you will get CmsSettings. But if you write this method with using static:

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

    return $results;
}

You will get instance of class which you're used for call run() - ChildCmsSettings.

Upvotes: 2

vishuB
vishuB

Reputation: 4261

Use self

Refer 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;
      }

   }
}

Upvotes: 1

Related Questions