gpt4 book ai didi

php返回全局变量

转载 作者:行者123 更新时间:2023-12-04 18:13:08 25 4
gpt4 key购买 nike

我有可以设置并包含一些字符串的变量,如果没有,我需要以另一种方式找到这个字符串。我决定将三元运算符与匿名函数一起使用,第一个函数在设置变量值时使用,第二个在没有设置时使用。

问题是,第一个函数没有返回任何值,为什么不呢?

// This line is just for testing purposes so the first anonymous function is run
$variable = "value test";

$variable = isset($variable) ?
function() { global $variable; return $variable; } :
function() {
$tmp = JFactory::GetDocument()->base;
$tmp = explode('/', JFactory::GetDocument()->base);
$tmp = explode('-', $tmp[count($tmp)-1]);
unset($tmp[0]);

return implode(' ', $tmp);
};

print_r($variable);

最佳答案

该函数可能不会返回任何内容,因为 $variable不是全局的,它存在于调用者的范围内。您需要将其作为参数传递,或者在调用者中也将其声明为全局。

但是为什么要使用两个匿名函数呢?你不能使用:

$variable = isset($variable) ? $variable : function(){...}

关于php返回全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12219975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com