2011-01-09 110 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陣列。