Reputation: 1457
I was wondering, I have a few functions in PHP that're not called every time but still are included in my files on each load. Does it still run the code even if your not calling the function at that time? The reason I'm asking, the codes in my function are expensive to run CPU wise and I don't call them every time and want to make sure if there not called they do not run the code within the function.
Thank you
Upvotes: 2
Views: 1413
Reputation: 1077
In short, a function that isn't explicitly called does not run. However, here is a short what and why we use functions that I found.
A function is a "black box" that we've locked part of our program into. The idea behind a function is that it compartmentalizes part of the program, and in particular, that the code within the function has some useful properties:
It performs some well-defined task, which will be useful to other parts of the program.
It might be useful to other programs as well; that is, we might be able to reuse it (and without having to rewrite it).
The rest of the program doesn't have to know the details of how the function is implemented. This can make the rest of the program easier to think about.
The function performs its task well. It may be written to do a little more than is required by the first program that calls it, with the anticipation that the calling program (or some other program) may later need the extra functionality or improved performance. (It's important that a finished function do its job well, otherwise there might be a reluctance to call it, and it therefore might not achieve the goal of reusability.)
By placing the code to perform the useful task into a function, and simply calling the function in the other parts of the program where the task must be performed, the rest of the program becomes clearer: rather than having some large, complicated, difficult-to-understand piece of code repeated wherever the task is being performed, we have a single simple function call, and the name of the function reminds us which task is being performed.
Since the rest of the program doesn't have to know the details of how the function is implemented, the rest of the program doesn't care if the function is reimplemented later, in some different way (as long as it continues to perform its same task, of course!). This means that one part of the program can be rewritten, to improve performance or add a new feature (or simply to fix a bug), without having to rewrite the rest of the program.
Functions are probably the most important weapon in our battle against software complexity. You'll want to learn when it's appropriate to break processing out into functions (and also when it's not), and how to set up function interfaces to best achieve the qualities mentioned above: reuseability, information hiding, clarity, and maintainability.
http://www.eskimo.com/~scs/cclass/notes/sx5.html
Upvotes: 3