(PHP 4, PHP 5, PHP 7, PHP 8)
require
和 include 几乎完全一样,除了处理失败的方式不同之外。require 在出错时产生 E_COMPILE_ERROR
级别的错误。换句话说将导致脚本中止而 include 只产生警告(E_WARNING
),脚本会继续运行。
参见 include 文档了解详情。
User Contributed Notes 26 notes
130
chris at chrisstockton dot org ¶
14 years ago
Remember, when using require that it is a statement, not a function. It's not necessary to write:
<?php
require('somefile.php');
?>
The following:
<?php
require 'somefile.php';
?>
Is preferred, it will prevent your peers from giving you a hard time and a trivial conversation about what require really is.
10
6 months ago
If your included file returns a value, you can get it as a result from require(), i.e.
foo.php:
<?php
return "foo";
?>
$bar = require("foo.php");
echo $bar; // equals to "foo"
0
15 years ago
A note that drove me nuts for 2 days!
Be carfull if you have a newline or blank space befor your php tags in the included/required file it will read as html and outputed.
If your running your output through javascript string evaluations which would be sensitive to newlines/white spaces be carfull that the first chars in the file are the php tages eg <?php
-9
6 years ago
PHP's require and include seem to differ from C's include in another way: they can't be used in the middle of an expression. e.g.
$ more foo1.php foo2.php
::::::::::::::
foo1.php
::::::::::::::
<?php
print "hello"
.
#"there"
require 'foo2.php';
. "\n";
?>
::::::::::::::
foo2.php
::::::::::::::
"there"
$ php foo1.php
PHP Parse error: syntax error, unexpected '.' in foo1.php on line 6
So php's include operates only on complete statements, whereas c's include operates on bytes of source code.
-8
richardbrenner(-at- )gmx(-)at ¶
16 years ago
If you use relativ paths in a php script (file A) that can be required by another php script (file B), be aware that the relativ paths in file A will be relativ to the directory, where file B is stored.
You can use the following syntax in file A, to be sure that the paths are relativ to the directory of file A:
<?
require(dirname(__FILE__)."/path/relative/file_to_include.php");
?>
Greetings,
Richard