PHP include() 返回值不一致还是我的无知?

发布于 2025-01-05 21:36:11 字数 754 浏览 0 评论 0原文

哦,好吧,也许这是我的无知,但是关于 include< 的 PHP 文档/a> 声明说比较返回值时要小心

<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
    echo 'OK';
}

// works
if ((include 'vars.php') == 'OK') {
    echo 'OK';
}
?>

但这就是我所经历的; boolean false 如果失败,int 1 如果成功:

$exists = 'Found.php';
var_dump((include $exists)); // Type is: int, value is: 1

$notexists = 'NotFound.php';
var_dump((include $notexists)); // Type is: boolean, value is: false

这是我的错吗?为什么返回值不一致(例如,并不总是布尔值)并且与 PHP 文档不同?

Oh well, maybe it's my ignorance, but PHP documentation about include statement says take care when comparing return value:

<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
    echo 'OK';
}

// works
if ((include 'vars.php') == 'OK') {
    echo 'OK';
}
?>

But this is what i've experienced; boolean false in case of fail, int 1 if success:

$exists = 'Found.php';
var_dump((include $exists)); // Type is: int, value is: 1

$notexists = 'NotFound.php';
var_dump((include $notexists)); // Type is: boolean, value is: false

Is this my bad? Why returning value is inconsistent (meaning not always boolean, for example) and differs from PHP documentation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浊酒尽余欢 2025-01-12 21:36:11

嗯,这正是文档中所述的内容:

$bar 的值为 1,因为包含成功。 ...
如果无法包含该文件,则返回 FALSE 并发出 E_WARNING。

当它变得不一致时,就是当你实际返回包含文件中的某些内容时,
例如在 Found.php 中:

<?php
return 'Returned from Found.php';

然后

include 'Found.php'; // -> Returns "Returned from Found.php"

还值得一读 PHP 中布尔值的计算方式:

http://php.net/manual/en/language.types.boolean.php

Well this is exactly what the documentation states:

$bar is the value 1 because the include was successful. ...
If the file can't be included, FALSE is returned and E_WARNING is issued.

When it becomes inconsistent is when you actually return something in the included file,
e.g. in Found.php:

<?php
return 'Returned from Found.php';

And then

include 'Found.php'; // -> Returns "Returned from Found.php"

It is also worth reading up on how booleans evaluate in PHP:

http://php.net/manual/en/language.types.boolean.php

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文