functions and not so global variables.

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

    functions and not so global variables.

    Hi,

    I want to tidy my code up a bit and in order to do that I need to break some
    function down.

    so if I have something like

    function function_1()
    {
    $foo = 0;
    $bar = 1;

    $foobar = $foo + $foo
    echo $foobar;
    }

    and I want to split it in two functions I would maybe get

    function function_2()
    {
    $foobar = $foo + $foo
    echo $foobar;
    }

    function function_1()
    {
    $foo = 0;
    $bar = 1;

    function function_2()
    }

    But of course the problem is that function_2 does not know what $foo and
    $bar are equal to because the values are not global.
    But how could I make function_2 know about the values defined in
    function_1()?

    The purpose is just to clean up the code so I do not want to do anything
    that might be a security problem.

    Many thanks in advance.

    Sims



  • J.O. Aho

    #2
    Re: functions and not so global variables.

    Sims wrote:
    [color=blue]
    > I want to tidy my code up a bit and in order to do that I need to break some
    > function down and I want to split it in two functions
    > But of course the problem is that function_2 does not know what $foo and
    > $bar are equal to because the values are not global.
    > But how could I make function_2 know about the values defined in
    > function_1()?[/color]

    function function_2($foo ,$bar) {
    $foobar = $foo + $foo
    echo $foobar;
    }

    function function_1() {
    $foo = 0;
    $bar = 1;

    function function_2($foo ,$bar)
    }

    Or if you want to be able to use default values:
    function function_2($foo =1,$bar=0) {
    $foobar = $foo + $foo
    echo $foobar;
    }

    function function_1() {
    $foo = 0;
    $bar = 1;

    function function_2($foo ,$bar)
    }

    function function_3() {
    /* can call the function_2() without arguments
    and foo will be 1 and bar would be 0 */
    function function_2()
    }


    //Aho

    Comment

    • Paul Delannoy

      #3
      Re: functions and not so global variables.

      Sims a écrit:[color=blue]
      > Hi,
      >
      >[...]
      > But of course the problem is that function_2 does not know what $foo and
      > $bar are equal to because the values are not global.
      > But how could I make function_2 know about the values defined in
      > function_1()?[/color]
      Just 'pass' the values as args to function_2 : function
      function_2($foo ,$bar)

      [color=blue]
      > Many thanks in advance.[/color]
      For nothing

      Comment

      Working...