confused of $this in cakePHP
I got a few lines of开发者_StackOverflow中文版 codes in a Model in cakePHP 1.26:
function beforeSave() {
$this->data['User']['pswd'] = md5($raw['User']['pswd']);
return true;
} // this beforeSave() works
The code above has been tested and it is working in my database.
Yet, I am not sure if I can understand it well, so, I re-wrote the code in other way, and it just failed to work then. function beforeSave() {
$raw=$this->data;
$raw['User']['pswd'] = md5($raw['User']['pswd']);
return true;
} // this beforeSave() failed to work
Why the second method can not work?
In this line:
$raw=$this->data
You're just assigning $this->data
by value to $raw
. So when you change $raw
's array data, $this->data
isn't affected by the change.
Besides, you're totally changing the meaning of your code. What you end up doing is replacing $raw
's data with $this->data
from your model. I've not worked with CakePHP before, but I assume $raw
already contains all the raw data you've received through some kind input, while $this->data
in your model contains the older version of your model data (for example, an older password that the user was going to change). Your changed code will just erase all the new data in $raw
, which I don't think is what you intend to do judging from your first code example.
To give you a little explanation of this line:
$this->data['User']['pswd'] = md5($raw['User']['pswd']);
It's pretty simple: the pswd
item in the User
array of $this->data
is set as the MD5 checksum of the pswd
in the User
array of $raw
.
if($this->data['Register']['password'] == $this->data['Register']['confirm_password'])
{
return true;
}
else
{
return false;
}
Use this in your model's beforeSave function()
精彩评论