Developing a module for drupal and I need to pass/modify variables within functions. I avoided using global variables because drupal uses the include function which subsequently makes my global variable into local.
As such, i created the following script which stores a static variable but I cannot retain the new value. Any help will be appreciated
function _example_set_flashurl($value = '21224', $clear = NULL) {
static $url;
if ($clear) {
// reset url variable back to default
$url = null;
}
//开发者_JAVA技巧 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
Try this
<?
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
You override the value in the empty call to set in your get function.
First, you probably want to add the default value directly to the static and not the argument. Like this: "static $url = '21224';". Then, this value will also be returned when set has never been called.
Second, there is no need for a $clear argument if you can pass in any value you want. If you want to change it, just override the old value.
Third, as the answer from bruce dou showed, you want to protect it against accidently overriding the value.
So, this code for the set function should be all you need:
<?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;
}
?>
精彩评论