Editing variables in parent function

So I think this is partly a scope problem, but it’s not as simple as that. I have one function that calls another function that is recursive, and each function, in addition to returning some data, also needs to edit a variable in the parent function. I think I could define the variable at the start of the page and use global, but there are some issues with that, too. I think some of the problem is also that I just don’t know the methods or functions that might exist that do what

But basically, I have one function that eventually calls a second function, and the second function is already responsible for returning an array, but in addition I need it to modify the values of a half-dozen variables in the parent function. I don’t think I can use global because the variables are defined within the parent function, not at the start of the page. What’s the best practice for this kind of thing?

It sounds like one or more of your functions has the wrong responsibility, and it actually contains part of your main application code.

Functions should be general-purpose, do one thing well, and be a building block to help you produce applications. If you find yourself constantly editing code or values inside of a function every time it gets used in a new application, on a different domain/server, or in a different context, that’s a sign the code is part of your main application code and doesn’t belong in a function/class.

Without more specific information, such as what the input data is, what processing you are going to do on the data, and what result you expect, it’s not possible to answer more specifically.

Tell us what the real problem is you are trying to solve instead of your attempted solution to the real problem.

Yeah, I think I’m doing it wrong. For a project of this size, it was a really bad idea to wing it and just try to go through it linearly without having an idea how I would use it later. I’ve thought about it more and realized that I can in fact pass all the needed information through the return, but I have to completely restructure how I’m doing this. I think maybe it would be a good idea to outline what I’m doing for the entire project before I dive into writing the code.

I wanted to post a direct example of the code, but the reality is that I’ve been cutting and pasting parts of functions all over the place, and it’s not even runnable right now because of this, and it would take pages just to be able to try to demonstrate what I’m trying to do, and I can’t ask anyone here to put that much time into this.

Time to start over, but I can at least re-use some snippets, so it wasn’t completely a wasted effort.

Thank you for the help.

Think of it this way, would you start building a house without first having blueprints drawn up?

Sponsor our Newsletter | Privacy Policy | Terms of Service