宜信同城网交流论坛

 找回密码
 立即注册
开启左侧

require 和 include 几乎完全一样,除了处理失败的方式不同之外。require 在出错时产 ...

[复制链接]
发表于 2023-2-16 18:54:50 | 显示全部楼层 |阅读模式 来自 LAN

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

require 和 include 几乎完全一样,除了处理失败的方式不同之外。require 在出错时产生 E_COMPILE_ERROR 级别的错误。换句话说将导致脚本中止而 include 只产生警告(E_WARNING),脚本会继续运行。

参见 include 文档了解详情。

正在上传…重新上传取消 add a note

User Contributed Notes 26 notes

up

down

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:
require('somefile.php');
?>

The following:
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.

up

down

10

Marcel Baur ¶

6 months ago

If your included file returns a value, you can get it as a result from require(), i.e.

foo.php:
return "foo";
?>

$bar = require("foo.php");
echo $bar; // equals to "foo"

up

down

0

Anonymous ¶

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

up

down

-9

dank at kegel dot com ¶

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
::::::::::::::
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.

up

down

-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

宜信网交流论坛 - 版权声明 1、在发表言论时,请遵守当地法律法规。主题所有言论纯属个人意见,与本站立场无关。
2、本站所有主题由作者发表,作者享有帖子相关版权,其他单位或个人使用、转载或引用本文时必须征得作者同意并注明来源于宜信网
3、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意。
4、帖子不遵守当地法律法规、广告、人身攻击等情况时,宜信网管理人员有权不事先通知发贴者而删除本文。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|宜信同城网交流论坛 ( 闽ICP备19021048号 )|站点地图

GMT+8, 2026-3-28 03:19 , Processed in 0.263928 second(s), 13 queries , Redis On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表