954,576 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Function variables

I made this function and the problem i have is that the Variavle $Time is not available to the whole program and what i mean by that is the function runs but doesn't set the variable to the whole thing and i have tested the function by doing echos.

Is there a way to set the variable in the function usable out side of the function.
[PHP]
function Times()
{
if (time() < mktime(12,00,00))
{
$Time = 'AM';
}
else
{
$Time = 'PM';
}
}
[/PHP]

ashneet
Junior Poster
147 posts since Jun 2005
Reputation Points: 10
Solved Threads: 1
 
I made this function and the problem i have is that the Variavle $Time is not available to the whole program and what i mean by that is the function runs but doesn't set the variable to the whole thing and i have tested the function by doing echos. Is there a way to set the variable in the function usable out side of the function. [PHP] function Times() { if (time() < mktime(12,00,00)) { $Time = 'AM'; } else { $Time = 'PM'; } } [/PHP]

By default, all variables used in functions are local variables, even if you use the same name of a global variable. You have to declare them global within the function. You can achieve this by adding this to the start of that function:

[PHP]
global $Time;
[/PHP]

-Fredric

Daishi
Junior Poster in Training
80 posts since Aug 2005
Reputation Points: 10
Solved Threads: 2
 

Thanks that helps a lot

ashneet
Junior Poster
147 posts since Jun 2005
Reputation Points: 10
Solved Threads: 1
 

rather than create a global variable I'd have done it this way

function Times()
{
  if (time() < mktime(12,00,00)) $Time = 'AM';
  else $Time = 'PM';
  return $Time;
}

$thisTime = Times();
sarahk
Junior Poster
144 posts since Apr 2005
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You