471,337 Members | 1,125 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,337 software developers and data experts.

HOWTO: use an array globally ?? (i want a function to work w/ it)

Bob
I've tried everything; and I can't seem to get past this VERY
(seemingly) simply problem.

I want to work with an array variable within a function(s).

I can't get it to work; if I:
1) global $arr=array(); (syntax err)
2) global $arr; in "main", the var isn't global
3) global $arr; in function, the array is cleared each time

I know I must be missing something REALLY simple/dumb; but just can't
seem to find it! any help appreciated!
tia - Bob

ei:
<?php
for ($x=1; $x<=2; $x++) {
print "\nloop # $x\n";
if($x==1) {
$row[1]="Why"; $row[2]="doesn't"; $row[3]="this work??";
$row[4]="this does"; }
if($x==2) {
$row[1]="This is"; $row[2]="the 2nd"; $row[3]="time thru.";
$row[4]="all done"; }

print "123before: 1:$arr[1] 2:$arr[2] 3:$arr[3] s:$s\n";
print "456before: 4:$arr[4] 5:$arr[5] 6:$arr[6] s:$s\n";
myf($x,$row);
print "123after : 1:$arr[1] 2:$arr[2] 3:$arr[3] s:$s\n";
print "456after : 4:$arr[4] 5:$arr[5] 6:$arr[6] s:$s\n";
}

function myf($x,$frow) {
global $arr, $s;
if ($x==1) { $arr=array(1=>$frow[1],2=>$frow[2],3=>$frow[3]);
$s=$frow[4]; }
if ($x==2) { $arr=array(4=>$frow[1],5=>$frow[2],6=>$frow[3]);
$s=$frow[4]; }
print "123during: 1:$arr[1] 2:$arr[2] 3:$arr[3] s:$s\n";
print "456during: 4:$arr[4] 5:$arr[5] 6:$arr[6] s:$s\n";
}
?>
Jul 17 '05 #1
15 2187
On Thu, 18 Mar 2004 08:35:24 -0600, Bob wrote:
I've tried everything; and I can't seem to get past this VERY
(seemingly) simply problem.

I want to work with an array variable within a function(s).

I can't get it to work; if I:
1) global $arr=array(); (syntax err)
2) global $arr; in "main", the var isn't global
3) global $arr; in function, the array is cleared each time


Where is $arr set? In the snippet of code you provided, I don't see it.

Here are some suggestions:

1) Try to avoid globals AS MUCH AS POSSIBLE!

2) If you must use globals, (and usually there is a better solution), use
the $GLOBALS array. It is a bit easier than declaring global(this, that,
the other) in your functions.

A much better solution IMO is to pass everything you need in to the
function as an argument. If you need to act on the value of an external
variable, you can still do this, but just pass it in as a *reference*
instead.

3) The strings you are printing may not work as you expect. When printing
indexed array items in a string either
a) use the concat operator, "dot" -> .
OR b) use curly braces around the indexed array item like so

print "Hello this is array item zero: ${arry[0]}\n";

Using array syntax inside a string without using curly braces is just
asking for trouble.

4) the global() builtin only works inside functions and cannot include
assignments in its use. That's why you are having trouble with your point
1 and 2.

Well, that's quite a bit of generalized stuff to chew on. Maybe it will
help, maybe it won't; if it doesn't, please come back with more stuff.

later...

--
Jeffrey D. Silverman | jeffrey AT jhu DOT edu
Website | http://www.wse.jhu.edu/newtnotes/

Jul 17 '05 #2
"Jeffrey Silverman" <je*****@jhu.edu> schrieb im Newsbeitrag
news:pa****************************@jhu.edu...
On Thu, 18 Mar 2004 08:35:24 -0600, Bob wrote:
[...]
Here are some suggestions:

1) Try to avoid globals AS MUCH AS POSSIBLE!

2) If you must use globals, (and usually there is a better solution), use
the $GLOBALS array. It is a bit easier than declaring global(this, that,
the other) in your functions.

A much better solution IMO is to pass everything you need in to the
function as an argument. If you need to act on the value of an external
variable, you can still do this, but just pass it in as a *reference*
instead.


I just started using globals and am very interested in the reason why it is
recommended to avoid them. In my actual project I have global informations,
such as:
- some variables for project-wide settings as the database connection string
and others
- an array which contains all the strings used for the user interface, so
that a translation of the whole project can be easily made by replacing that
array

It is very handy to pass this information to the function with "global
$variable" - what is the problem with it? From the point of view of code
readability IMO it is easier to pass only the arguments that are specific to
the function.

It is all about information that is used but not modified by the function.
For variables with setting information I see the alternative of using
constants, but constants can't contain arrays, or am I wrong with that?

--
Markus
Jul 17 '05 #3
Bob
On Thu, 18 Mar 2004 09:47:14 -0500, Jeffrey Silverman
<je*****@jhu.edu> wrote:
On Thu, 18 Mar 2004 08:35:24 -0600, Bob wrote:
I've tried everything; and I can't seem to get past this VERY
(seemingly) simply problem.

I want to work with an array variable within a function(s).

I can't get it to work; if I:
1) global $arr=array(); (syntax err)
2) global $arr; in "main", the var isn't global
3) global $arr; in function, the array is cleared each time
Where is $arr set? In the snippet of code you provided, I don't see it.


hi Jeff ! - tx so much for your reply; please excuse my
middle-posting; but it seems easiest to address your points.

the $arr array is set within the function "myf".
1) Try to avoid globals AS MUCH AS POSSIBLE!
as a general rule, I do try to do this; but this has really become a
question of principle; not programming excellence...
2) If you must use globals, (and usually there is a better solution), use
the $GLOBALS array. It is a bit easier than declaring global(this, that,
the other) in your functions.
this I knew about, but originally thought it was easier using
global().
A much better solution IMO is to pass everything you need in to the
function as an argument. If you need to act on the value of an external
variable, you can still do this, but just pass it in as a *reference*
instead.
agreed; my REAL problem evolved into this little exercise in
experimentation.
3) The strings you are printing may not work as you expect. When printing
indexed array items in a string either
a) use the concat operator, "dot" -> .
OR b) use curly braces around the indexed array item like so

print "Hello this is array item zero: ${arry[0]}\n";

Using array syntax inside a string without using curly braces is just
asking for trouble.
I normally do use the concat operator; but I did NOT know that using
variables inside a string could be problematic - I appreciate that
information!!!!
4) the global() builtin only works inside functions and cannot include
assignments in its use. That's why you are having trouble with your point
1 and 2.
this too, was my understanding. #'s 1&2 only came about because #3
wasn't working...
Well, that's quite a bit of generalized stuff to chew on. Maybe it will
help, maybe it won't; if it doesn't, please come back with more stuff.


your reply was very informative! I definitely learned a few new
things. I'm still curious, however, about the intended use of
global().

If using global within a function unsets the var it's globalling, then
be definition that function can only be used once without losing what
you want to keep global !?

IF I were to solve my code snip problem; IS there a solution that
doesn't use the $GLOBAL var?

tia (again!) - Bob
Jul 17 '05 #4
Bob wrote:
I've tried everything; and I can't seem to get past this VERY
(seemingly) simply problem.

I want to work with an array variable within a function(s).

I can't get it to work; if I:
1) global $arr=array(); (syntax err)
2) global $arr; in "main", the var isn't global
3) global $arr; in function, the array is cleared each time

I know I must be missing something REALLY simple/dumb; but just can't
seem to find it! any help appreciated!


Check this out - it may be of some help for you:

http://www.koivi.com/manual-php-globals/

--
Justin Koivisto - sp**@koivi.com
PHP POSTERS: Please use comp.lang.php for PHP related questions,
alt.php* groups are not recommended.
SEO Competition League: http://seo.koivi.com/
Jul 17 '05 #5
In general it violates the "encapsulation" principle.
Your function is no longer self-contained and it relies upon some external
information which some other function may change in an unexpected way.
It also no longer has control over variable naming and there could be naming
conflicts.
For example, you may use someone else's function library and it could contain
the same global variable name, but it is used for a different reason, so you
have to rewrite one of the libraries to resolve the name conflict.

Not using globals is not an absolute rule, and you can probably get away with it
for small projects, but for large projects with multiple developers using
globals should be considered very very very poor design.
The best thing to do is just not to get in the habit of using globals.

That said, it is common practice to hold certain settings in an "include" file,
such as database connection variables.

Regarding your translation array -- perhaps it would be better if it were held
in a database table.
That would allow an easy selection in the application of which language to use,
and would allow updates by an administrator without changing code.
Or put it inside of a function or an object in an included library and make
calls to the function or use an object method when you need information from the
array.

Dave
"Markus Ernst" <derernst@NO#SP#AMgmx.ch> wrote in message
news:40**********************@news.easynet.ch...
I just started using globals and am very interested in the reason why it is
recommended to avoid them. In my actual project I have global informations,
such as:
- some variables for project-wide settings as the database connection string
and others
- an array which contains all the strings used for the user interface, so
that a translation of the whole project can be easily made by replacing that
array

It is very handy to pass this information to the function with "global
$variable" - what is the problem with it? From the point of view of code
readability IMO it is easier to pass only the arguments that are specific to
the function.

It is all about information that is used but not modified by the function.
For variables with setting information I see the alternative of using
constants, but constants can't contain arrays, or am I wrong with that?

--
Markus

Jul 17 '05 #6
With total disregard for any kind of safety measures "Markus
Ernst" <derernst@NO#SP#AMgmx.ch> leapt forth and uttered:
I just started using globals and am very interested in the
reason why it is recommended to avoid them.


http://www.c2.com/cgi/wiki?GlobalVariablesAreBad

--
Phil Roberts | Dork Pretending To Be Hard | http://www.flatnet.net/
Jul 17 '05 #7
On Thu, 18 Mar 2004 16:22:18 +0100, Markus Ernst wrote:
I just started using globals and am very interested in the reason why it
is recommended to avoid them. In my actual project I have global
informations, such as:
- some variables for project-wide settings as the database connection
string and others
IMO, these are not "variables", that is to say they will not change. Use
*constants* for this purpose:

define('DATABASE_USER', 'boogerboy');
define('DATABASE_PASSWORD', 'yourmomma');

etc...
- an array which contains all the strings used for the user interface, so
that a translation of the whole project can be easily made by replacing
that array


Not sure quite what you meant for this. Still, if it is never going to
change, a constant works better than a variable.

gotta go...wife is mad at me! later...

--
-------------------------
| Jeffrey Silverman |
| jeffrey-AT-jhu-DOT-edu|
-------------------------

Jul 17 '05 #8
"Phil Roberts" <ph*****@HOLYflatnetSHIT.net> schrieb im Newsbeitrag
news:Xn*************************@216.196.97.132...
With total disregard for any kind of safety measures "Markus
Ernst" <derernst@NO#SP#AMgmx.ch> leapt forth and uttered:


Well there is a safety measure in my e-mail address ;-)
I just started using globals and am very interested in the
reason why it is recommended to avoid them.


http://www.c2.com/cgi/wiki?GlobalVariablesAreBad


Thanks for that interesting link.

--
Markus
Jul 17 '05 #9
"Jeffrey Silverman" <je*****@jhu.edu> schrieb im Newsbeitrag
news:pa****************************@jhu.edu...
On Thu, 18 Mar 2004 16:22:18 +0100, Markus Ernst wrote:
I just started using globals and am very interested in the reason why it
is recommended to avoid them. In my actual project I have global
informations, such as:
- some variables for project-wide settings as the database connection
string and others


IMO, these are not "variables", that is to say they will not change. Use
*constants* for this purpose:

define('DATABASE_USER', 'boogerboy');
define('DATABASE_PASSWORD', 'yourmomma');

etc...
- an array which contains all the strings used for the user interface, so that a translation of the whole project can be easily made by replacing
that array


Not sure quite what you meant for this. Still, if it is never going to
change, a constant works better than a variable.


Thank you and the other posters for your very interesting points, I learnt a
lot now.

The translation works like that:

I have a file per supported language. It builds an array of all strings used
in the administration tool. The file "english.php" could look like that:
$ls['back']="back";
$ls['submit']="submit";
The file "deutsch.php" would say:
$ls['back']="zur&uuml;ck";
$ls['submit']="abschicken";

In the language choosing script I just list the contents of the directory
called "languagefiles" and give the administrator the possibility to choose
his/her preferred language, and after that the appropriate language file
will be included in the head of every page. The code at the page then just
says: <input type="submit" value="<?php echo $ls['submit']; ?>">

And in any function where I need language-specific strings I declare $ls as
global.

Like that I can easily add a translation without entering hundreds of
entries into a database.

I think after having read all postings in the thread that special case seems
to be ok, as the language information is not changed and cannot be stored in
a constant either. Anyway maybe it would be better practice to include the
$ls array into every function call.

--
Markus
Jul 17 '05 #10
Uzytkownik "Markus Ernst" <derernst@NO#SP#AMgmx.ch> napisal w wiadomosci
news:40***********************@news.easynet.ch...
I think after having read all postings in the thread that special case seems to be ok, as the language information is not changed and cannot be stored in a constant either. Anyway maybe it would be better practice to include the
$ls array into every function call.


A better practice is to call a function to get the text. That way you hide
the implementation details from the rest of the site. As it is, your entire
codebase is dependent on the fact that the text strings are stored in an
associative array.

See http://www.php.net/manual/en/ref.gettext.php
Jul 17 '05 #11
Phil Roberts wrote:

[snipped]
Phil, I just took a quick peek at your website. FYI, your first paragraph
appears to have one too many periods.
Welcome to Flatnet. We focus on the creation of attractive, accessible
and functional websites. That combine dynamic content generation to
keep the visitors returning, and powerful administrative tools for the
webmaster to make updates and changes.


Just wanted to make you aware.
--
Joel Farris | Q: It reverses the logical flow of conversation.
twinkledust Designs | A: Why is top posting frowned upon?
http://twinkledust.com |
AIM chat: FarrisJoel |
| (this fifth line in my sig angers the net kops!)

Jul 17 '05 #12
Joel Farris wrote:
Phil Roberts wrote:

[snipped]
Phil, I just took a quick peek at your website. FYI, your first paragraph
appears to have one too many periods.
Welcome to Flatnet. We focus on the creation of attractive, accessible
and functional websites. That combine dynamic content generation to
keep the visitors returning, and powerful administrative tools for the
webmaster to make updates and changes.

Just wanted to make you aware.


At least his website works. ;)

-Jay

Jul 17 '05 #13
Jay Moore wrote:
Joel Farris wrote:
Phil, I just took a quick peek at your website. FYI, your first paragraph
appears to have one too many periods.
Welcome to Flatnet. We focus on the creation of attractive, accessible
and functional websites. That combine dynamic content generation to
keep the visitors returning, and powerful administrative tools for the
webmaster to make updates and changes.


Just wanted to make you aware.

At least his website works. ;)

-Jay

Too true! :-) His works better than the one I'm currently developing. Once
I slog through about 600 more of the recent posts, I'll have a question or
two for the group.
--
Joel Farris | Q: It reverses the logical flow of conversation.
twinkledust Designs | A: Why is top posting frowned upon?
http://twinkledust.com |
AIM chat: FarrisJoel |
| (this fifth line in my sig angers the net kops!)

Jul 17 '05 #14
With total disregard for any kind of safety measures Joel Farris
<th*********@valid.address> leapt forth and uttered:
Phil, I just took a quick peek at your website. FYI, your first
paragraph appears to have one too many periods.
Just wanted to make you aware.


Thanks, I'm aware that the wording isn't 100% as yet. I'm still
looking into ways I can better phrase things.

--
Phil Roberts | Dork Pretending To Be Hard | http://www.flatnet.net/
Jul 17 '05 #15
Bob
On Thu, 18 Mar 2004 16:16:03 GMT, Justin Koivisto <sp**@koivi.com>
wrote:
http://www.koivi.com/manual-php-globals/


thank you, Justin;

a very interesting article!

Bob

Jul 17 '05 #16

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Matthew Jakeman | last post: by
29 posts views Thread by Ancient_Hacker | last post: by
5 posts views Thread by bearophileHUGS | last post: by
9 posts views Thread by Pallav singh | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.