PHP和DRUPAL,无法在静态变量中保存值并通过函数

时间:2011-03-17 05:31:26

标签: php drupal

为drupal开发模块,我需要在函数中传递/修改变量。我避免使用全局变量,因为drupal使用include函数,随后将我的全局变量变为local。

因此,我创建了以下脚本来存储静态变量,但我无法保留新值。任何帮助将不胜感激

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 

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以覆盖在get函数中设置的空调用中的值。

首先,您可能希望将默认值直接添加到静态而不是参数。像这样:“static $ url ='21224';”。然后,当从未调用set时,也将返回此值。

其次,如果您可以传入任何您想要的值,则不需要$ clear参数。如果要更改它,只需覆盖旧值。

第三,正如布鲁斯的回答所显示的那样,你想要保护它免受意外地压倒价值。

因此,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;
}
?>