每當我使用$model->attributes=$_POST['Users']
時,它都會保存來自User窗體的數據。
當我使用$model->setAttributes($_POST['Users'])
時,它也保存來自用戶窗體的數據。
那麼請誰能澄清兩個代碼之間的區別?
每當我使用$model->attributes=$_POST['Users']
時,它都會保存來自User窗體的數據。
當我使用$model->setAttributes($_POST['Users'])
時,它也保存來自用戶窗體的數據。
那麼請誰能澄清兩個代碼之間的區別?
如Yii wiki所述,您可以使用其中任何一種。用$model->attributes
可以直接設置變量。通過$model->setAttributes()
,您可以通過所謂的「setter方法」來設置變量。
http://www.yiiframework.com/wiki/167/understanding-virtual-attributes-and-get-set-methods/#hh1
我會使用setter方法,而不是直接調用的變量,你可以在你的setter方法添加一條線,這將適用於所有的呼叫,它會幫你逃脫很多頭痛在未來。
例子:
class Model {
public $attributes;
public function setAttributes($attributes) {
$this->attributes = $attributes;
}
public function getAttributes() {
return $this->attributes;
}
}
$model = new Model();
$model->setAttributes("Foo");
echo $model->getAttributes();
$model->setAttributes("Bar");
echo $model->getAttributes();
所以,現在如果你想使對屬性的附加操作,你可以將它添加到setAttributes()
方法,而不是改變兩行代碼,你可以改變只有一個。
例子:
class Model {
public $attributes;
public function setAttributes($attributes) {
$this->attributes = $attributes . "-Bar";
}
public function getAttributes() {
return $this->attributes;
}
}
$model = new Model();
$model->setAttributes("Foo");
echo $model->getAttributes();
$model->setAttributes("Bar");
echo $model->getAttributes();
現在這個規模達的水平,當它會帶來不便更改數千行代碼,而不是改變一對夫婦的setter方法。
絕對沒有區別。
當您嘗試分配未在component定義爲PHP類屬性(如attributes
這裏)的屬性,通過Yii中調用約定的類似名稱的setter方法setAttributes
代替。如果不存在這樣的方法,則拋出異常。由於Yii模型是一個組件,並且模型沒有attributes
屬性,因此即使在使用第一個窗體時也會調用setter方法。
本手冊中所有這些也都是explained in detail。
請確認您的回答中包含必要的鏈接部分,因爲鏈接已知會在一段時間內死亡。 – 2014-09-02 13:23:33
@CaffeineCoder:我想我已經做到了。 – Jon 2014-09-02 13:25:35
我指的是那裏提到的例子。 – 2014-09-02 13:27:46
$model->attributes=$_POST['Users']// means setting value of property directly while
$model->setAttributes($_POST['Users']) //is method or function which is indirectly set value of $model->attributes property;
讓我們舉一個例子
class Model{
public $attributes;
public function setAttributes($att){
$this->attributes=$att;
}
}
//Now the value of $attributes can be set by two way
$model = new Model();
$model->attributes=$value; // 1st way
$model->setAttributes($value); //2nd way
隨着$this->setAttributes()
可以分配不安全屬性,使用$this->attributes
你不能。
分配不安全屬性:在
$this->setAttributes($_POST['Model'], false);
更多信息:http://www.yiiframework.com/doc/api/1.1/CModel/#setAttributes-detail
我很滿意你的回答@Marcos。 – 2014-09-03 04:58:07
沒有區別。 array_merge用於合併屬性,如果以後設置
我只是猜測,但'setAttributes()'還應該運行一些驗證規則。 – Narf 2014-09-02 13:13:37