2011-03-17 39 views
0

爲drupal開發模塊,我需要在函數中傳遞/修改變量。我避免使用全局變量,因爲drupal使用包含函數,隨後將我的全局變量變爲本地變量。PHP和DRUPAL,無法將值保存在靜態變量中並通過函數

因此,我創建了下面的腳本,它存儲了一個靜態變量,但我不能保留新的值。任何幫助將不勝感激

function _example_set_flashurl($value = '21224', $clear = NULL) { 
    static $url; 

    if ($clear) { 
    // reset url variable back to default 
    $url = null; 
    } 
    // assigned url a perminate value within this function 
    $url = $value; 
    return $url; 


} 

function _example_get_flashurl() { 
    return _example_set_flashurl(); 
    // retrieve the value inside set scope 
} 
_example_set_flashurl('another', TRUE); 
print _example_get_flashurl(); // prints 21224, I want it to print another 

回答

1

試試這個

<? 
function _example_set_flashurl($value = '21224', $clear = NULL) { 
    static $url; 

    if ($clear) { 
    // reset url variable back to default 
    $url = null; 
    } 
    if($value!='21224') { 
    // assigned url a perminate value within this function 
    $url = $value; 
    } 
    return $url; 


} 

function _example_get_flashurl() { 
    return _example_set_flashurl(); 
    // retrieve the value inside set scope 
} 
_example_set_flashurl('another', TRUE); 
print _example_get_flashurl(); // prints 21224, I want it to print another 
0

您在空呼叫覆蓋該值在get函數來設置。

首先,您可能希望將默認值直接添加到靜態而不是參數。像這樣:「static $ url ='21224';」。然後,當設置從未被調用時,該值也將被返回。

其次,如果您可以傳入任何您想要的值,則不需要$ clear參數。如果你想改變它,只需重寫舊的值。

第三,正如布魯斯杜的回答所顯示的那樣,您希望保護它免於意外地壓倒價值。

所以,此代碼爲設置的功能應該是所有您需要:

<?php 
function _example_set_flashurl($value = FALSE) { 
    static $url = '21224'; 

    // Only keep value if it's not FALSE. 
    if ($value !== FALSE) { 
    // assigned url a perminate value within this function 
    $url = $value; 
    } 
    return $url; 
} 
?> 
+0

感謝,所有的解決方案都工作正常。 BUt只有在我將變量傳遞到「相同頁面」時才起作用。我的意思是在相同頁面加載的兩個不同函數之間設置和獲取變量。但我通過ajax請求傳遞這些變量,當我打印變量 - $ url。它打印21224. – amedjones 2011-03-17 19:17:08

+0

我只設法通過variable_set和variable_get得到這個工作。但是這是一個性能問題,因爲每次使用variable_Set時都會清除表。任何其他建議?全球也不工作,它吐出默認值 – amedjones 2011-03-17 19:18:22

+0

這是設計。 PHP是無狀態的,請求之間沒有任何共享。如果它是用戶特定的,則可以將其保存在$ _SESSION中。是的,variable_get/set的意思是「一次寫入(多或少)/經常讀」的東西。 – Berdir 2011-03-17 19:20:52