曾几何时,看着顺眼就用,没有思考过里面的差异,后面有个产景使用到了才思考了起来,用不好问题很严重的!
参考:new self() 和 new static() 的区别_Yee Jason的博客-CSDN博客_new static
他们的区别只有在继承中才能体现出来、如果没有任何继承、那么二者没有任何区别;
然后 new self() 返回的实列是不会变的,无论谁去调用,都返回的一个类的实列,
而 new static则是由调用者决定的。
如果一个项目中,要求根据不同商户获取其唯一的配置实例,而你又不清楚他是否存在继承关系必须用 $instance = new static();
class MpStoreConfig extends MchModel
{
public $store_id;
public $app_id;
public $p_id;
public $app_auth_token;
const OPTION_KEY = 'config';
public function rules()
{
return [
[['app_id', 'p_id', 'cs_scene', 'other_accounts', 'goods_no_list'], 'trim'],
];
}
public function attributeLabels()
{
return [
'app_id' => '小程序AppID',
'p_id' => '账号id',
'app_auth_token' => '授权token',
'key' => '加密方式密钥'
];
}
public function save()
{
if (!$this->validate()) {
return $this->getErrorResponse();
}
$data = $this->attributes;
unset($data['store_id']);
Option::set(self::OPTION_KEY, $data, $this->store_id);
return [
'code' => 0,
'msg' => '保存成功。',
];
}
/**
* 根据 Store Id 获取其配置实例
*
* @param string|int $storeId
* @return static
*/
public static function get($storeId)
{
$instance = new static();
$instance->store_id = $storeId;
$data = Option::get(self::OPTION_KEY, $storeId);
if ($data != null) {
$instance->attributes = (array)$data;
}
return $instance;
}
}
这样保证唯一实例!如果涉及一些重要的配置!必须这样做