View Full Version : Variable Scope
11-21-2007, 12:33 AM
I have a variable that I declared outside a function. How can I access the variable from inside the function?
11-21-2007, 01: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.)
11-21-2007, 05: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.
11-21-2007, 09:55 PM
Can you tell me why this code isn't working. When I run it, nothing is displayed.
function sequence ($x,$counter)
if ($x == 1)
if ($x % 2 == 0)
sequence(3*$x + 1,$counter);
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.
you need a 'return' in front of the recursive calls:
if ($x % 2 == 0)
(and the same on the other one)
Powered by vBulletin® Version 4.2.2 Copyright © 2015 vBulletin Solutions, Inc. All rights reserved.