0

拜托,你能帮我解决我的问题吗?

我有一个名为 Translateable 的类,然后是 Article 和 Banner 类,它们扩展了这个类。

当我这样做时,就会出现问题:

$article = (new Article)->find(15);
$banner =  (new Banner)->find(1);

$articleTrans = $article->trans(); // method trans is method from Translateable

当我打电话时,$article->trans();我期望这样的输出:

App\Models\ArticleTrans
Article

但它返回这个:

App\Models\ArticleTrans
Banner

第一行没问题,但第二行如果不好,我不知道如何解决这个问题。我需要将$instance存储为静态属性。

你能给我你的帮助吗?

  class Translateable extends Model {

        static $transLang = null;
        static $transClass = null;
        static $instance = null;

        public function __construct(array $attributes = array()) {

            static::$transLang = App::getLocale();

            parent::$transClass = static::$transClass;
            parent::$instance = static::$instance;
            parent::__construct($attributes);

        }
        /**
         * get items trans
         *
         * @param null $lang
         * @return mixed
         */
         public function trans($lang = null) {
              if($lang == null) {
                 $lang = static::$transLang;
              }

                  echo static::$transClass;
                  echo class_basename(static::$instance);
                  die();

              }
              public static function find($primaryKeyVal, $columns = []) {

                 $tci = new static::$transClass;
                 $item = static::withTrans()->where(static::$instance->getTable() . '.' . static::$instance->primaryKey, '=', $primaryKeyVal)->where($tci->getTable() . '.lang', '=', static::$transLang)->first();
    return $item;

        }
    }

class Article extends Translateable {
        static $transClass = 'App\Models\ArticleTrans';

        public function __construct(array $attributes = array()) {

            parent::$transClass = static::$transClass;
            parent::$instance = $this;

            parent::__construct($attributes);

        }
 }

class Banner extends Translateable {

    static $transClass = 'App\Models\BannerTrans';

    public function __construct(array $attributes = array()) {

        parent::$transClass = static::$transClass;
        parent::$instance = $this;

        parent::__construct($attributes);

    }
}
4

0 回答 0