...

View Full Version : Variable Scope



MindTheGap
11-21-2007, 01:33 AM
I have a variable that I declared outside a function. How can I access the variable from inside the function?

CFMaBiSmAd
11-21-2007, 02:04 AM
The correct method is to pass everything a function (or a class) needs as parameters in the function call. This allows functions (or a class) to be general purpose and reusable without any need to setup specifically named variables which could conflict with something the program is already using that variable for or another function (or class) that could be using a variable with the same name.

When you write programs with several hundred or several thousand lines of code, you cannot be juggling variable names just because they have been used inside of functions or rewrite known working functions (or classes) to change a variable name just because any name has already been used.

Consider the case of all the php functions. To the best of my recollection, NONE of them require you to setup a specifically named variable in your code before you call the function that then uses that variable inside of the function.

In case you still want to do what you asked, I will leave it up to you to look up and read in the php manual how to do this (it's in there for anyone to find once they look.)

Velox Letum
11-21-2007, 06:10 AM
CFMaBiSmAd is correct. Accessing an external variable isn't the best way to go about things. Superglobals such as $_POST are accessible. Globals can be used but just pass things you need through the function call.

MindTheGap
11-21-2007, 10:55 PM
Thank you!

Can you tell me why this code isn't working. When I run it, nothing is displayed.


function sequence ($x,$counter)
{

if ($x == 1)
{
return $counter;
}
else
{
if ($x % 2 == 0)
{
$counter++;
sequence($x/2,$counter);
}
else
{
$counter++;
sequence(3*$x + 1,$counter);
}
}
}
echo sequence(13,0);


I'm trying to solve this problem by the way:
The following iterative sequence is defined for the set of positive integers:

n n/2 (n is even)
n 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:
13 40 20 10 5 16 8 4 2 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.

GJay
11-21-2007, 11:09 PM
you need a 'return' in front of the recursive calls:


if ($x % 2 == 0)
{
$counter++;
return sequence($x/2,$counter);
}

(and the same on the other one)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum