Getting Vars value from function
I am using this function;
function forums_fid()
{
if (!defined('FORUMS_FID'))
{
$maktaba_fid = '14';
$ask_question_fid = '9';
}
define('FORUMS_FID', 1);
}
I want to use the values โโof variables in another function, so I am trying to use this code for that;
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>';
Bur unfortunately the variables are empty in this second code.
Please, help!
+3
source to share
3 answers
Forget what I said earlier. What you can do is define two empty variables (NULL) and declare them global in the function, overwrite them with whatever you want, and then use them. By the way, you need to put define () inside if-clausel or PHP will throw an error.
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>';
This is one way. The best way would be to actually return the values โโ(e.g. as an array).
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>';
+3
source to share
I would recommend a super variable . $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:
Documentation:
+1
source to share