Function parameter

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

    Function parameter

    Hi,

    I'm new to PHP and have a small problem. Assume you define a function
    that is called with a constant as parameter. Within that function, based
    on some condition it calls itself recursively. Example:

    <?php

    function Test($firstcall ) {
    echo "(enter) firstcall=$firs tcall<br>\n";

    if (some_condition ) {
    Test(0);
    }

    echo "(leave) firstcall=$firs tcall<br>\n";
    }

    Test(1);

    ?>

    I need that variable/parameter before and after the main part of the
    function. For the first call, the (enter) output shows that $firstcall=1,
    but the (leave) always shows $firstcall=0, if the function has been
    called recursively. I don't use parameters by reference but by value. So
    how must I declare $firstcall correctly to maintain its content within
    subsequent calls?
    As tha parameter name says, it only should be 1 for the first (= the
    outside) call.

    Thanks for enlightening a newbie :-)

    - Michael

  • Tom Thackrey

    #2
    Re: Function parameter


    On 26-Sep-2003, Michael Kochendoerfer <mk@isp.hem.d e> wrote:
    [color=blue]
    > I'm new to PHP and have a small problem. Assume you define a function
    > that is called with a constant as parameter. Within that function, based
    > on some condition it calls itself recursively. Example:
    >
    > <?php
    >
    > function Test($firstcall ) {
    > echo "(enter) firstcall=$firs tcall<br>\n";
    >
    > if (some_condition ) {
    > Test(0);
    > }
    >
    > echo "(leave) firstcall=$firs tcall<br>\n";
    > }
    >
    > Test(1);
    >
    > ?>
    >
    > I need that variable/parameter before and after the main part of the
    > function. For the first call, the (enter) output shows that $firstcall=1,
    > but the (leave) always shows $firstcall=0, if the function has been
    > called recursively. I don't use parameters by reference but by value. So
    > how must I declare $firstcall correctly to maintain its content within
    > subsequent calls?
    > As tha parameter name says, it only should be 1 for the first (= the
    > outside) call.[/color]

    Are you sure you get firstcall=0 from the first iteration?

    I tried your code, after changing the condition to i($firstcall==1 ), and got
    the following:
    <?php

    function Test($firstcall ) {
    echo "(enter) firstcall=$firs tcall<br>\n";

    if ($firstcall==1) {
    Test(0);
    }

    echo "(leave) firstcall=$firs tcall<br>\n";
    }

    Test(1);

    ?>

    (enter) firstcall=1
    (enter) firstcall=0
    (leave) firstcall=0
    (leave) firstcall=1


    --
    Tom Thackrey

    Comment

    Working...