Search code examples
phprequire-once

A practical scenario for using include(), include_once() and require() constructs


Among include, include_once, require and require_once I always just use require_once. Many third-party frameworks just use require_once as well.

Can anybody please describe a real scenario that another construct must be used?


Solution

  • IMHO there is no real scenario that fits include and include_once because of two reasons:

    1. It's highly unlikely that your intention is to include a file and at the same time you don't really care if it's included (e.g. if the file does not exist and execution continues).
    2. Even if that is the case, include will emit a warning which is bad style (zero-warning code is a good thing to strive for). You can prevent this most of the time with a check like is_file, but then you know that the file does exist so why not require it?

    For require vs require_once: if a file can legitimately be parsed more than once (e.g. an HTML template) use the former. If it brings code inside your application (the vast majority of cases) use the latter.