Where do I place include_once in a PHP app?

2019-09-02 07:20发布

问题:

I have a simple PHP app and also a class which contains some config settings like DB conn string and some paths. Where would I best place the include_once('config/config.php'); code?

Thanks

回答1:

There is a PHP setting called auto_prepend_file which you can make use of. Set it to a file that is the bootstrap of your scripts:

bootstrap.php

<?php
/* 
 * bootstrap
 *
 * this file will be always loaded first.
 */

include(__DIR__.'/config/config.php');

You can then later on include everything your application needs to work.

If you don't want to use that ini setting, you can as well in all your scripts just include the bootstrap.php file at the very top:

user/profile.php

<?php
/*
 * show profile of a user
 */
require(__DIR__.'/../bootstrap.php'); # bootstrap

It's generally a good idea to have a central point at the very start in your application, this is commonly called bootstrap.



回答2:

I like to use Front Controller pattern with one entry point. And in this point I create an instance of Config class, that includes Db config and others.



回答3:

You need to include files before using anything inside them.

So beginning of a file is a generally good spot.



回答4:

If you don't have many files, just put everything in the same source directory.

Otherwise, "include" or "inc" are common names. Usually in parallel with "src" and "imgs"; under the root of your app.

But why not just using "config", like in your example? Sounds like a perfectly appropriate place to me :)



回答5:

Depends on the situation. usually near the top. That is most used but there are some cases you want to include only if some settings are met.

you then can include it where you need it but it is less clean.

In your case config should be included on top for the most clean solution.

Also note that you need to include it before you can use the variables inside config file. This is the reason why includes are done at the top of the file.



回答6:

Theoretically speaking, you can include files anywhere in the PHP code given that you use it only after including.

However, in practice I have generally seen include at two places.

  1. If it is just a plain file with no functions, then it is generally placed at the top of the file. This improves readability of the code. Also anyone who is starting to read your code, will know at the start of the external dependencies.

  2. If there are functions, then too at the beginning of the function - by the same logic as above. Note here it is included inside the function rather than at the top-level of the file. This is mainly because other functions might not be needing it. Even if they do, I think keeping include separate for each function makes the functions more modular - all dependencies in the function.