user6394229
user6394229

Reputation:

How to structure the PHP files?

In order to avoid repeated coding in the page's elements like (header or sidebar), I have to include() them in the PHP main files... However, if both the header and the sidebar are including [functions.php] - for example - and are both included in multiple pages, then I will receive a "redeclared functions" error!

How can the structure be in PHP in order to avoid too much coding, and also use (include) the functions in those included pages?!

Upvotes: 0

Views: 98

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57131

As your project becomes more complex, it will become impossible to find there is only one place that you can include a file. So deciding that file a.php is included only in file b.php becomes unmanageable. Especially if you start having files with things like a User class, where this is referenced from several other classes.

Consider using require_once, this will not only mean that it's only pulled into the code once, but that if the file isn't found it will produce a fatal error and stop, whereas include_once won't.

A common use of this would be to load the configuration or autoloading, a lot of my project files will have...

require_once '../vendor/autoload.php';
require_once __DIR__ . '/config.php';

as the first lines of the script.

Upvotes: 2

Shaunak Shukla
Shaunak Shukla

Reputation: 2347

You can include it in the header only, the sidebar will have included that page default from the header as the main page is having both elements included.
Simple!!!

Upvotes: 0

Related Questions