3

Is there any way to use a variable of a method, after a recursive call (without sending that as a parameter).

For example:

class Doc {

    public function readDoc($file, $recursion = false) {
        if ($recursion != false) {
            // DO SOMETHING;
        }
        $filename = $file."Some added text";
        $this->readDoc($filename, 1);
    }
}

Here, is it possible to use the value of $file sent in the first call (when the readDoc() function is called recursively).

0

2 Answers 2

1

You can create a simple stack with an array, e.g.

  class Doc {
    private $stack = [];

    public function readDoc($file, $recursion=false) {
          if($recursion != false)    
              DO SOMETHING

          $this->stack[] = $file;    
          $filename = $file."Some added text";
          $this->readDoc($filename, 1);
    }
}

And then get the first index of the array as your $file variable.

Sign up to request clarification or add additional context in comments.

Comments

0

you could also use an anonymous function to work in a different scope something like this:

public function test($file, $recursion = false)
{
    $rec = function($r) use ($file, &$rec)
    {
        if($r !== false) {

        }

        $filename = $file.'test';
        return $rec($r);
    };

    return $rec($recursion);
}

in this case the $file variable always stays the same (be aware that the above example creates an infinite-loop)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.