为了说明Destructor的概念,如果值在对象被销毁之前发生了变化,那么在下面的代码块中给出了更新数据库的概念:
<?php
class use {
private $_properties;
private $_changedProperties //Keeps a list of the properties that were altered
private $_hDB;
//_construct and __get omitted for brevity
function __set($propertyName, $value) {
if(!array_key_exists($propertyName, $this->_properties))
throw new Exception('Invalid property value!');
if(method_exists($this, 'set'. $propertyName)) {
return call_user_func(
array($this, 'set', $propertyName), $value);
}
else {
//If the value of the property really has changed
//and it's not already in the changedProperties array,
//add it.
if($this->_properties[$propertyName] !=$value && !in_array($propertyName, $this->_changedProperties)) {
$this->_changedProperties[] = $propertyName;
}
其余代码是不必要的代码,已被省略。请从以下点解释代码:
if(method_exists($this, 'set'. $propertyName)) {
return call_user_func(
array($this, 'set', $propertyName), $value);
}
else {
//If the value of the property really has changed
//and it's not already in the changedProperties array,
//add it.
if($this->_properties[$propertyName] !=$value && !in_array($propertyName, $this->_changedProperties)) {
$this->_changedProperties[] = $propertyName;
}
为什么我这样问,我想验证我对代码的解释/理解。
答案 0 :(得分:0)
你的注释说明看起来是正确的...但这与实际的析构函数没什么关系,尽管我假设析构函数检查changedProperties成员并在有破坏之前写入它们。但这与你的问题并不完全相关,所以我认为你提到它会引起混淆。
答案 1 :(得分:0)
粗略地说,这段代码检查是否有一个setter(一个在属性上设置值的方法),该属性的名称由参数$propertyName
给出,如果不存在这样的函数,它会添加属性到包含名为_changedProperties
的数组的字段。
更准确地说:假设$propertyName
包含字符串"Foo"
if(method_exists($this, 'set'. $propertyName)) {
如果此对象具有名为setFoo
return call_user_func(array($this, 'set', $propertyName), $value);
使用第一个参数setFoo
调用方法$value
并返回其结果;相当于调用return $this->setFoo($value);
,但文字Foo
由$propertyName
参数化。
}else{
基本上,此对象没有名为setFoo
的方法。
if($this->_properties[$propertyName] != $value
&& !in_array($propertyName, $this->_changedProperties)) {
如果此属性的值(Foo
)的存储值与我现在知道的存储值不同,则它不会显示在_changedProperties
数组
$this->_changedProperties[] = $propertyName;
将此属性的名称添加到已更改属性的列表中。 (此处,将Foo
添加到_changedProperties
数组。