簡體   English   中英

PHP和DRUPAL,無法將值保存在靜態變量中並通過函數

[英]PHP and DRUPAL, Cannot save values in a static variable and pass through function

為drupal開發一個模塊,我需要在函數內傳遞/修改變量。 我避免使用全局變量,因為drupal使用include函數,該函數隨后將我的全局變量轉換為局部變量。

這樣,我創建了以下腳本,該腳本存儲了一個靜態變量,但是我無法保留新值。 任何幫助將不勝感激

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 

嘗試這個

<?
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

您可以在空調用中覆蓋要在get函數中設置的值。

首先,您可能希望將默認值直接添加到static而不是參數中。 像這樣:“靜態$ url ='21224';”。 然后,當從未調用過set時,也將返回此值。

其次,如果可以傳遞任何所需的值,則不需要$ clear參數。 如果要更改它,只需覆蓋舊值即可。

第三,正如布魯斯·杜(Bruce dou)的回答所顯示的那樣,您想保護它以防意外覆蓋其價值。

因此,set函數的這段代碼應該是您所需要的:

<?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;
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM