Fwrite()错误:提供的参数不是有效的流资源.为什么


fwrite() error: supplied argument is not a valid stream resource. Why?

我有这样的代码:

$file = '/path/to/file.txt';
if (($fd = fopen($file, "a") !== false)) {
    fwrite($fd, 'message to be written' . "'n");
    fclose($fd);
}

为什么我得到以下警告?

fwrite(): supplied argument is not a valid stream resource
fclose(): supplied argument is not a valid stream resource

你的if语句是错误的。试着

if (($fd = fopen($file, "a")) !== false) {

因为你的就像

$fd = fopen($file, "a") !== false

因为括号错误。代码应该是:

if (($fd = fopen($file, "a")) !== false) {

当前代码所做的是将$fd设置为fopen返回值与false比较的结果,也就是false(假设fopen成功)。实际上你有

if ($fd = false) {

这是自解释的,也是可测试的(与var_dump)。

这个故事的寓意是:不要给if条件中的变量赋值。现在不是1980年,你也不是在用c编程。只要说不,让核心可读;它会因此爱上你的。