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

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

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:
<?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 <?php

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值