Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why include when you can require in PHP?

Tags:

php

What is the point of attempting to include or include_once a library in PHP if you often have to use require or require_once instead (as they're usually critically important)?

like image 870
locoboy Avatar asked May 17 '11 05:05

locoboy


People also ask

How failures in execution are handled with include () and require () functions?

How failures in execution are handled with include() and require() functions? If the function require() cannot access to the file then it ends with a fatal error. However, the include() function gives a warning and the PHP script continues to execute.

Why include is not working in PHP?

You need to try the path of functions. php within the system and not its url. Do you have console access? If so just find out what directory is the file in and include it using the full path.

What is the use of require once in PHP?

The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.


2 Answers

Sometimes you are including files from libraries that you do not control or your code is being run on different environments.

It is possible that some of these aren't actually required for your script but are helper files or extras.

For instance, if your PHP is generating HTML, you might use an include to add a banner. But you wouldn't want your file to halt if for some reason that banner file was missing. You'd want to gracefully fail instead.

like image 150
jopke Avatar answered Oct 14 '22 04:10

jopke


The difference between include/include_once and require/require_once is that when a file is not found, the former triggers a warning whereas the latter triggers an error. Opinions may vary but IMO, if a needed file is not present or readable for some reason, this represents a very broken situation and I would rather see an error and halt execution, than have a warning and proceed execution in a clearly broken context. So I believe it to be best practice to use require/require_once exclusively and avoid include/include_once altogether.

like image 27
Asaph Avatar answered Oct 14 '22 05:10

Asaph