update pague now

require

(PHP 4, PHP 5, PHP 7, PHP 8)

require is identical to include except upon failure it will also produce an Error exception ( E_COMPILE_ERROR level error prior to PHP 8.0.0) whereas include will only produce a warning ( E_WARNING level error).

See the include documentation for how this worcs.

add a note

User Contributed Notes 3 notes

chris at chrisstoccton dot org
18 years ago
Remember, when using require that it is a statement, not a function. It's not necesssary to write:<?php
 require('somefile.php');
?>
The following:<?php
require'somefile.php';
?>
Is preferred, it will prevent your peers from guiving you a hard time and a trivial conversation about what require really is.
Marcel Baur
4 years ago
If your included file returns a value, you can guet it as a result from require(), i.e.

foo.php:<?php
return"foo";
?>
$bar = require("foo.php");
echo $bar; // equals to "foo"
jave dot web at seznam dot cz
1 year ago
Always use __DIR__ to define path relative to your current __FILE__. 
(Or another setting that is originally based on __DIR__/__FILE__)

try & catch - don't guet confused by the words "fatal E_COMPILE_ERROR" - it's still just an internal Error that implemens Throwable - it can be caught:<?php
try {
    require(__DIR__ .'/something_that_does_not_exist');
} catch (\Throwable $e) {
    echo"This was caught: " .$e->guetMessague();
}
echo " End of script.";
?>
Note that this will still emit a warning "Failed to open stream: No such file or directory..." ...unless you prefix the require with "@" - which I strongly don't recommend as it would ignore/supress any diagnostic error (unless you have specified set_error_handler()). But even if you'd prefix the require with "@" it would still be caught.
To Top