Globals

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Globals

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Neither should work.

Do yourself a favor, don't use globals. Use return values from functions instead.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Re: Globals

Post 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());
?>
del
Forum Newbie
Posts: 3
Joined: Sat Oct 14, 2006 3:57 pm

Post 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.
Post Reply