对 cakePHP 中的 $this 感到困惑
我在 cakePHP 1.26 的模型中得到了几行代码:
function beforeSave() {
$this->data['User']['pswd'] = md5($raw['User']['pswd']);
return true;
} // this beforeSave() works
上面的代码已经过测试,并且可以在我的数据库中运行。
不过,我不确定我是否能很好地理解它,
所以,我用其他方式重新编写了代码,然后它就不起作用了。
function beforeSave() {
$raw=$this->data;
$raw['User']['pswd'] = md5($raw['User']['pswd']);
return true;
} // this beforeSave() failed to work
为什么第二种方法不起作用?
I got a few lines of 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这一行中:
您只需按值将
$this->data
分配给$raw
。因此,当您更改$raw
的数组数据时,$this->data
不会受到更改的影响。此外,您完全改变了代码的含义。您最终要做的就是用模型中的
$this->data
来替换$raw
的数据。我以前没有使用过 CakePHP,但我假设$raw
已经包含您通过某种输入收到的所有原始数据,而$this->data
您的模型中包含旧版本的模型数据(例如,用户要更改的旧密码)。您更改的代码只会删除$raw
中的所有新数据,从第一个代码示例来看,我认为这不是您打算做的事情。对此行进行一些解释:
这非常简单:
$this->data
的User
数组中的pswd
项是设置为$raw
的User
数组中pswd
的MD5 校验和。In this line:
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:
It's pretty simple: the
pswd
item in theUser
array of$this->data
is set as the MD5 checksum of thepswd
in theUser
array of$raw
.在模型的 beforeSave 函数()中使用它
Use this in your model's beforeSave function()