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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bob

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

    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";
    }
    ?>


  • Jeffrey Silverman

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

    On Thu, 18 Mar 2004 08:35:24 -0600, Bob wrote:
    [color=blue]
    > 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[/color]

    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/

    Comment

    • Markus Ernst

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

      "Jeffrey Silverman" <jeffrey@jhu.ed u> schrieb im Newsbeitrag
      news:pan.2004.0 3.18.14.47.10.9 77402@jhu.edu.. .[color=blue]
      > On Thu, 18 Mar 2004 08:35:24 -0600, Bob wrote:[/color]

      [...]
      [color=blue]
      > 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.[/color]

      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


      Comment

      • Bob

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

        On Thu, 18 Mar 2004 09:47:14 -0500, Jeffrey Silverman
        <jeffrey@jhu.ed u> wrote:
        [color=blue]
        >On Thu, 18 Mar 2004 08:35:24 -0600, Bob wrote:
        >[color=green]
        >> 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[/color]
        >
        >Where is $arr set? In the snippet of code you provided, I don't see it.[/color]

        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".
        [color=blue]
        >1) Try to avoid globals AS MUCH AS POSSIBLE![/color]

        as a general rule, I do try to do this; but this has really become a
        question of principle; not programming excellence...
        [color=blue]
        >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.[/color]

        this I knew about, but originally thought it was easier using
        global().
        [color=blue]
        >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.[/color]

        agreed; my REAL problem evolved into this little exercise in
        experimentation .
        [color=blue]
        >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.[/color]

        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!!!!
        [color=blue]
        >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.[/color]

        this too, was my understanding. #'s 1&2 only came about because #3
        wasn't working...
        [color=blue]
        >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.
        >[/color]

        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


        Comment

        • Justin Koivisto

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

          Bob wrote:
          [color=blue]
          > 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![/color]

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



          --
          Justin Koivisto - spam@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/

          Comment

          • Dave Darden

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

            In general it violates the "encapsulat ion" 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:4059bead$0 $3615$afc38c87@ news.easynet.ch ...
            [color=blue]
            > 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
            >
            >[/color]


            Comment

            • Phil Roberts

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

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



              --
              Phil Roberts | Dork Pretending To Be Hard | http://www.flatnet.net/

              Comment

              • Jeffrey Silverman

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

                On Thu, 18 Mar 2004 16:22:18 +0100, Markus Ernst wrote:
                [color=blue]
                > 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[/color]

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

                define('DATABAS E_USER', 'boogerboy');
                define('DATABAS E_PASSWORD', 'yourmomma');

                etc...
                [color=blue]
                > - 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[/color]

                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|
                -------------------------

                Comment

                • Markus Ernst

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

                  "Phil Roberts" <philrob@HOLYfl atnetSHIT.net> schrieb im Newsbeitrag
                  news:Xns94B0C30 2E5FE6philrober ts@216.196.97.1 32...[color=blue]
                  > With total disregard for any kind of safety measures "Markus
                  > Ernst" <derernst@NO#SP #AMgmx.ch> leapt forth and uttered:[/color]

                  Well there is a safety measure in my e-mail address ;-)
                  [color=blue][color=green]
                  > > I just started using globals and am very interested in the
                  > > reason why it is recommended to avoid them.[/color]
                  >
                  > http://www.c2.com/cgi/wiki?GlobalVariablesAreBad
                  >[/color]

                  Thanks for that interesting link.

                  --
                  Markus


                  Comment

                  • Markus Ernst

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

                    "Jeffrey Silverman" <jeffrey@jhu.ed u> schrieb im Newsbeitrag
                    news:pan.2004.0 3.19.04.20.52.6 52077@jhu.edu.. .[color=blue]
                    > On Thu, 18 Mar 2004 16:22:18 +0100, Markus Ernst wrote:
                    >[color=green]
                    > > 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[/color]
                    >
                    > IMO, these are not "variables" , that is to say they will not change. Use
                    > *constants* for this purpose:
                    >
                    > define('DATABAS E_USER', 'boogerboy');
                    > define('DATABAS E_PASSWORD', 'yourmomma');
                    >
                    > etc...
                    >[color=green]
                    > > - an array which contains all the strings used for the user interface,[/color][/color]
                    so[color=blue][color=green]
                    > > that a translation of the whole project can be easily made by replacing
                    > > that array[/color]
                    >
                    > Not sure quite what you meant for this. Still, if it is never going to
                    > change, a constant works better than a variable.[/color]

                    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.ph p" could look like that:
                    $ls['back']="back";
                    $ls['submit']="submit";
                    The file "deutsch.ph p" would say:
                    $ls['back']="zur&uuml;c k";
                    $ls['submit']="abschicken ";

                    In the language choosing script I just list the contents of the directory
                    called "languagefi les" 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


                    Comment

                    • Chung Leong

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

                      Uzytkownik "Markus Ernst" <derernst@NO#SP #AMgmx.ch> napisal w wiadomosci
                      news:405abb0d$0 $10784$afc38c87 @news.easynet.c h...[color=blue]
                      > I think after having read all postings in the thread that special case[/color]
                      seems[color=blue]
                      > to be ok, as the language information is not changed and cannot be stored[/color]
                      in[color=blue]
                      > a constant either. Anyway maybe it would be better practice to include the
                      > $ls array into every function call.[/color]

                      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


                      Comment

                      • Joel Farris

                        #12
                        Re: HOWTO: use an array globally ??

                        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.
                        [color=blue]
                        > 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.[/color]

                        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!)

                        Comment

                        • Jay Moore

                          #13
                          Re: HOWTO: use an array globally ??

                          Joel Farris wrote:[color=blue]
                          > 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.
                          >[color=green]
                          >> 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.[/color]
                          >
                          >
                          > Just wanted to make you aware.[/color]

                          At least his website works. ;)

                          -Jay

                          Comment

                          • Joel Farris

                            #14
                            Re: HOWTO: use an array globally ??

                            Jay Moore wrote:
                            [color=blue][color=green]
                            >> Joel Farris wrote:
                            >> Phil, I just took a quick peek at your website. FYI, your first paragraph
                            >> appears to have one too many periods.
                            >>[color=darkred]
                            >>> 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.[/color]
                            >>
                            >> Just wanted to make you aware.[/color]
                            >
                            >
                            > At least his website works. ;)
                            >
                            > -Jay[/color]


                            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!)

                            Comment

                            • Phil Roberts

                              #15
                              Re: HOWTO: use an array globally ??

                              With total disregard for any kind of safety measures Joel Farris
                              <this.is.not@va lid.address> leapt forth and uttered:
                              [color=blue]
                              > 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.[/color]

                              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/

                              Comment

                              Working...