2011-03-17 36 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