为什么 yaml_parse_file 返回 true?

Why is yaml_parse_file returning true?

出于某种原因,当我 运行 .php 脚本时:

$s = yaml_parse_file("../config.yaml") || die("YAML file not found");
var_dump($s);

它returns:

bool(true)

这到底是怎么回事?这是突然发生的,它在一个星期内工作正常,但我似乎无法修复它。我已经使用 pecl install yaml 安装并将 "extension=yaml.so" 添加到 php.ini?

我使用过在线 yaml 正则表达式测试器,他们 return 没问题。格式是(显然有内容):

title: 
email: hello@
logo: images/logo.png
download-file: .dmg
recaptcha:
  pub:
  priv:
meta:
  keywords: mac, osx
  description:
  ico: images/icon.ico

您将布尔运算的结果赋值给 $s,因为 || 运算符的优先级高于赋值。所以评估如下:

$s = (yaml_parse_file("../config.yaml") || die("YAML file not found"));

这 returns 正确,因为初始表达式 returns 一个 "truthy" 值。

如果您将作业括在括号中,它将按您的预期工作:

($s = yaml_parse_file("../config.yaml")) || die("YAML file not found");
...

https://eval.in/960405

该代码以前有效,当它用于阅读时:

$s = yaml_parse_file("../config.yaml") or die("YAML file not found");

您最近将 or 更改为 ||(为什么?)而不知道它们是不同的运算符并且它们具有 different precedence.

or 具有最低的优先级,上面的表达式被计算为:

($s = yaml_parse_file(...)) or die(...)

|| 的优先级高于赋值 (=),问题中的表达式计算为:

 $s = (yaml_parse_file(...) || die(...))

要解决这个问题,首先你应该忘记or die()。这是 15 多年前 PHP 教程传播的不良编码实践。令人遗憾的是,他们中的许多人仍然可以在网络上使用,并教新手如何在发生错误时将白页扔到访问者的脸上。

or die()没用。如果 yaml_parse_file()(或使用它调用你 "handle" 的任何函数)returns FALSE,下一个尝试使用结果的语句很可能无论如何都会失败。您将在 php_errors.log 中收到或多或少的描述性错误消息。该错误消息可帮助您调试代码并识别和修复错误。 or die 没有任何帮助。它只是将错误隐藏在地毯下,并告诉访问者他们可以自己看到的内容:您的网站无法运行。但它不会告诉您错误是什么或如何修复它。