PHP静态属性,扩展类被覆盖

时间:2016-05-29 21:03:12

标签: php oop static extending extending-classes

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

我有一个名为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);

    }
}

0 个答案:

没有答案