Page 1 of 1
Globals
Posted: Sat Oct 14, 2006 9:20 am
by impulse()
How is it possible to access a global variable from function A inside of function B?
I have:
Code: Select all
function A()
{
$varOne = 10;
}
A();
echo $varOne;
And this works fine
But if I have
Code: Select all
function A()
{
$varOne = 10;
}
function B()
{
echo $varOne;
}
It returns empty data.
Posted: Sat Oct 14, 2006 9:23 am
by feyd
Neither should work.
Do yourself a favor, don't use globals. Use return values from functions instead.
Re: Globals
Posted: Sat Oct 14, 2006 8:33 pm
by Luke
Code: Select all
<?php
function function_A()
{
// Declare $varOne in function_A() and return it's value
$varOne = 10;
return $varOne;
}
function function_B($input)
{
// Accept input, and print it out
echo $input;
}
// Send the return value from function_A() to function_B()... no need for globals
function_B(function_A());
?>
Posted: Sat Oct 14, 2006 11:48 pm
by del
Is this what you're after?
Code: Select all
$varOne = 0;
function A()
{
global $varOne;
$varOne = 10;
}
function B()
{
global $varOne;
echo $varOne;
}
A();
B(); // Emits 10
Note that use of globals in functions is not a recommended style.