Include all functions in the php file I need or ju

2020-07-13 11:44发布

问题:

So here is what I want to do.

  1. The first option is to write each function in different php file each one and then include all of them in a php file that is called include functions.php and whenever I create a new page , let's say index.php I just include "functions.php";

    Why do I need to do that? Because I'll just have to include only one file and all the functions will be included. Now the problem probably will be the server load. I'm not sure how much uncalled functions affect the performance.

  2. The second option is to create again the files I need, team them up and then whenever I need a function just call it. The drawback of this is that I'll have more work to do in order to categorize and I'll have to include a lot of files

So I want to ask, does the first option increase the cpu and memory load that much that I have to go to the second one? Are there any performance issues with the first way or the functions that are not being used are not parsed at all by the php ?

回答1:

Disk is a slowest part of the server, so in this case variant "all functions in 1 file" will give you little more performance, theoretically.

But I don't recommend you to create "functions.php", better way is OOP. Create classes (objects) with methods, use autoloaders and PSR-0 standard and you will forget about "include" and "require" at all.



回答2:

This is a time to remember Donald Knuth's famous quote:

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."

In general, your development model should be tuned to match the needs and goals of the project. After you have met the goals, you can always return to such questions as the one you asked. When you do that, your question will probably answer itself. The program structure will dictate the best way to handle your includes.

You may wish to consider using object-oriented programming (OOP) if it is applicable to your project. Whenyou use OOP, this problem may even become a non issue if your objects handle their own dependency loading.