|
-
Apr 15th, 2010, 08:40 PM
#1
Thread Starter
Hyperactive Member
[RESOLVED] php5 - global variable clarification
Code:
$a = 1;
$b = 2;
function nekkidrage()
global $a, $b;
exit()
Will $a = 1 and $b = 2 in the function? If so is this the best approach?
-
Apr 15th, 2010, 11:14 PM
#2
Re: php5 - global variable clarification
yes, they will be available to the function. this approach is perfectly fine. you could also use the $GLOBALS array, but I prefer the method you posted.
PHP Code:
function sum(){ return $GLOBALS['a'] + $GLOBALS['b']; }
more on variable scope
-
Apr 16th, 2010, 12:13 AM
#3
Re: php5 - global variable clarification
I prefer not to use globals — for things which require global access, I use static variables in classes.
This approach gives you organisation: you can have a settings class, a database class, and so on.
A function to me should be self-contained (unlike a class method). It should be stateless and deterministic — the same input should always give the same output — unless it is specifically otherwise (such as a pseudo-random algorithm).
Last edited by penagate; Apr 16th, 2010 at 12:16 AM.
-
Apr 16th, 2010, 12:14 AM
#4
Thread Starter
Hyperactive Member
Re: php5 - global variable clarification
 Originally Posted by penagate
I prefer not to use globals — for things which require global access, I use static variables in classes.
This approach gives you organisation: you can have a settings class, a database class, and so on.
A function to me should be self-contained (unlike a class method). This means it takes input (arguments) and returns output, which doesn't depend on any other factors.
Baby steps for me dude, learning php as I go. Maybe next verison of the software
-
Apr 16th, 2010, 12:18 AM
#5
Re: php5 - global variable clarification
That's general advice, not just for PHP. Your approach is perfectly valid; I'm just offering another viewpoint.
Objects exist to provide state and so my opinion is that any function which requires state should be a class method.
-
Apr 16th, 2010, 12:21 AM
#6
Thread Starter
Hyperactive Member
Re: php5 - global variable clarification
 Originally Posted by penagate
That's general advice, not just for PHP. Your approach is perfectly valid; I'm just offering another viewpoint.
Objects exist to provide state and so my opinion is that any function which requires state should be a class method.
Not dissing the approach, simply stating there's a time factor involved so as much as I might like to add all the decent programming approaches I don't have time to learn them all.
-
Apr 16th, 2010, 11:14 AM
#7
Re: php5 - global variable clarification
Nice function name, by the way...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|