2011-01-09 87 views
0

为了说明析构函数,如果该对象之前的值的变化被破坏下面的代码块被书中给出一个数据库被更新的概念:解释简单的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; 
    } 

为什么我问这是我想验证我对代码的理解/理解。

回答

0

你的评论笔记似乎是正确的...但这与实际的析构函数没有多大关系,但我假定析构函数检查changedProperties成员,并且在破坏之前写入它们。但那不是真的与你的问题有关,所以我认为你提到它会引起混淆。

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阵列。