[英]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.