解释简单的PHP代码
问题描述:
为了说明析构函数,如果该对象之前的值的变化被破坏下面的代码块被书中给出一个数据库被更新的概念:解释简单的PHP代码
<?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;
}
为什么我问这是我想验证我对代码的理解/理解。
答
你的评论笔记似乎是正确的...但这与实际的析构函数没有多大关系,但我假定析构函数检查changedProperties成员,并且在破坏之前写入它们。但那不是真的与你的问题有关,所以我认为你提到它会引起混淆。
答
粗略地说,这段代码检查是否有一个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
阵列。