简体   繁体   中英

php including file practice

Should I still write the includes that a php file needs if they will already be included before hand by other php files executed prior?

For example, let's say I have 3 php files : parent.php , child.php, and food.php.

parent.php and child.php need the functions located in food.php. parent.php first includes food.php and then child.php. That means child.php will have food.php loaded for it as well.

So for child.php should I still write require_once/include_once('food.php'), or leave it out?

Thanks.

在您的示例中, child.php不需要包含food.php

It'll be a good idea to include the files individually. If for some reason, food.php did not get included in parent.php , your code in child.php won't work.

To prevent this, you can load food.php in both the files, so if one fails, the other file will work smoothly.

Renaming the files will make it more clear.

functions.php:

//some code

file1.php:

require_once('functions.php');
//some code

file2.php:

require_once('functions.php');
//some code

Ideally you will know where files are being including, based on a framework or even just simple file structure.

Just including files here and there "just in case you forgot" is really bad coding practice. Where do you draw the line? Set meta tags in header.php, but then also in index.php just in case it doesn't work in header.php?

You could use require_once() instead, which will halt on error (whereas include_once will continue to do the remaining scripts) - such as:

PHP Fatal error: require_once(): Failed opening required 'food.php'

While PHP should obey and only include "once", it could cause issues re-including a file again, errors/warnings etc, so just structure your files correctly and include files in files when you need them (usually all at the top of the file which requires them)

If I understood you correctly, you just need parent.php to include food.php first, THEN child.php, and therefore both parent.php and child.php will have access to whatever is in food.php.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM