我正在使用此功能;
function forums_fid()
{
if (!defined('FORUMS_FID'))
{
$maktaba_fid = '14';
$ask_question_fid = '9';
}
define('FORUMS_FID', 1);
}
我想在另一个函数中使用变量值,所以为此我尝试使用此代码;
forums_fid();
$maktaba = '<a href="www.domain.com/forumdisplay.php?fid='.$maktaba_fid.'"><img src="./images/maktaba.png" alt="" title=""></a>';
$ask_question = '<a href="www.domain.com/newthread.php?fid='.$ask_question_fid.'"><img src="./images/ask-question.png" alt="" title=""></a>';
不幸的是,在第二段代码中,变量是空的。
请帮忙!
答案 0 :(得分:3)
忘记我之前说过的话。你可以做的是定义两个空变量(NULL)并在函数中将它们声明为全局变量,用你想要的任何东西覆盖它们然后使用它们。顺便说一下,你必须在if-clausel中放置define(),否则PHP会抛出错误。
function forums_fid()
{
global $maktaba_fid, $ask_question_fid;
if (!defined('FORUMS_FID'))
{
define('FORUMS_FID', 1);
$maktaba_fid = '14';
$ask_question_fid = '9';
}
}
$maktaba_fid = NULL;
$ask_question_fid = NULL;
forums_fid();
$maktaba = '<a href="www.domain.com/forumdisplay.php?fid='.$maktaba_fid.'"><img src="./images/maktaba.png" alt="" title=""></a>';
$ask_question = '<a href="www.domain.com/newthread.php?fid='.$ask_question_fid.'"><img src="./images/ask-question.png" alt="" title=""></a>';
这是一种方式。更好的方法是实际返回值(例如,作为数组)。
function forums_fid()
{
if (!defined('FORUMS_FID'))
{
define('FORUMS_FID', 1);
return array('maktaba_fid' => 14, 'ask_question_fid' => 9);
}
}
$return = forums_fid();
$maktaba = '<a href="www.domain.com/forumdisplay.php?fid='.$return['maktaba_fid'].'"><img src="./images/maktaba.png" alt="" title=""></a>';
$ask_question = '<a href="www.domain.com/newthread.php?fid='.$return['ask_question_fid'].'"><img src="./images/ask-question.png" alt="" title=""></a>';
答案 1 :(得分:1)
我会推荐 $GLOBALS
超级变量。
function forums_fid()
{
if (!defined('FORUMS_FID'))
{
$GLOBALS['maktaba_fid'] = '14';
$GLOBALS['ask_question_fid'] = '9';
}
define('FORUMS_FID', 1);
}
forums_fid();
echo $GLOBALS['maktaba_fid'].PHP_EOL;
echo $GLOBALS['ask_question_fid'];
的 DEMO:强>
的文档:强>
答案 2 :(得分:1)
试试这个
function forums_fid()
{
global $maktaba_fid;
global $ask_question_fid;
if (!defined('FORUMS_FID'))
{
$maktaba_fid = '14';
$ask_question_fid = '9';
define('FORUMS_FID', 1);
}
}